Where to place JavaScript Code in HTML?

This post explains clearly how can we inject JavaScript code into HTML head location or Body location or using separate Javascript files using suitable examples. This post also explains what are the advantages and disadvantages of .js file and centralization of javascript code.


JavaScript Code in HTML:

  • There are 3 general areas that JavaScript can be placed.
    1. Inside the head tag.
    2.Within the body tag.
    3. In an external file.
  • The location choice of head or body is very simple.
  • If you want to have a script run on some event, such as when a user clicks somewhere, then you will place that script in the head.
  • If you want the script to run when the page loads, then you will want to place the script within the body tag.

 

1) Inside the head tag :

<html>
<head>
<script type=”text/javascript”>
alert(document.getElementsByTagName(“li”).length);
</script>

<title>Web Technologies</title>
</head>
<body>
<p>These technologies need to learn..</p>
<ul>
<li>HTML</li>
<li>CSS</li>
<li>JavaScript</li>
</ul>
</body>
</html>

 

2) Inside the body tag :

<html>
<head>
<title>Web Technologies</title>
</head>
<body>
<p>These technologies need to learn..</p>
<ul>
<li>HTML</li>
<li>CSS</li>
<li>JavaScript</li>
</ul>

<script type=”text/javascript”>
alert(document.getElementsByTagName(“li”).length);
</script>
</body>
</html>

 

3) Importing an external file :

  • It is relatively painless.
  • First, the file you are importing must be valid JavaScript and only JavaScript.
  • Second, the file must have the file extension “.js”.
  • Lastly, you must know the location of the file.

 

HTML file :
<html>
<head>
<script src=”myjs.js”>
</script>
</head>
<body>
<input type=”button” onclick=”popup()” value=”Click Me!”>
</body>
</html>

myjs.js :
function popup()
{
alert(“Hello World”)
}

 

External File Tips :

  • Use external JavaScript files to centralize the javascript code for all HTML pages.
  • Use external JavaScript files for head location information and body location information.
  • JavaScript files should have .js extension.

> Dynamic Text into HTML page using JavaScript < 

Share this