JavaScript – Placement

Where to place JavaScript

JavaScript code must be placed between <script></script> tags in html. It can be placed in the <body>, or in the <head> section of HTML page, or in both.
Example:

<html>
<head>
<script>
alert(“Hello World”);
</script>
<head>
<body></body>
</html>



Functions in JavaScript

Function is a block of code, we can write user defined functions in JavaScript in JavaScript. A function can be called when an event occurs, like on button click.

Example:

<html>
<head>
<title>Html JavaScript</title>
<script>
function welcome() {
document.getElementById(“msg”).innerHTML = “Welcome to JavaScript!”;
}
</script>
</head>
<body>
<input type=”button” onclick = “welcome()” value=”Click Me”/>
<br/>
<span id=”msg”></span>
</body>
</html>


External JavaScript

Like external CSS we can also keep JavaScript code in a separate file and then include it in required html document. External scripts are very useful when the same code or javascript function used in many different web pages.

External javascript file must be save with .js extension.

To import the external javascript file src (source) attribute of a <script> tag is used:

Example:

External file: externalScript.js

<script>
function welcome() {
document.getElementById(“msg”).innerHTML = “Welcome to JavaScript!”;
}
</script>
<html>
<body>
<script src=”externalScript.js”></script>
<input type=”button” onclick = “welcome()” value=”Click Me”/>
<span id=”msg”>Hello World</span>
</body>
</html>


External JavaScript Advantages

  • JavaScript code as well as HTML code is easily readable
  • External JavaScript files are cached by browsers and can speed up page load times.
  • Designers can work along with coders parallel without code conflicts

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.