The correct place to Insert a JavaScript Code
In this article, we will see where is the correct place to insert JavaScript in HTML. We know that we can insert JavaScript codes in HTML using <script> tag. But Someone has the confusion where we should place the <script> tag. this is the right place to know that.
If you have a small JavaScript code, you can insert it directly above the closing body tag as in the below code.
Ex:
<html>
<head>
<title>Demo</title>
</head>
<body>
<p id="demo">HELLO EVERYONE</p>
<script type="text/javascript">
document.getElementById("demo").style.backgroundColor = "red";
</script>
</body>
</html>
Output:
In the above example, we have created a <p> tag inside the body section. Then we set the red background color to paragraph text using JavaScript, inside the <script> tag.
If we place <script> inside the before closing </body> tag, the red background color will be perfectly displayed as in the above output.
What happens if you place script elements in the head?
If we put <script> into <head> tag, the red background color won’t be displayed. Because the JavaScript code is present before “<p>” control. So, by the time the JS code is executed the <p> tag is still not loaded into the browser DOM (Document Object Model). That’s the reason, that piece of JavaScript code is not able to find the ID name “demo” and throws the null reference error. We got the same result if you insert <script> after opening <body> tag. So, that’s why where we insert JavaScript code is important.
Ex:
<html>
<head>
<title>Demo</title>
<script type="text/javascript">
document.getElementById("demo").style.backgroundColor = "red";
</script>
</head>
<body>
<p id="demo">HELLO EVERYONE</p>
</body>
</html>
Output:

When we insert<script> tag into the head section?
If you have a JavaScript code of more than 25 lines, you should put the code into an external file. If you have a JavaScript external file, you can insert the <script> tag into the <head> or <body> section.
<html>
<head>
<title>DEMO</title>
<script type="text/javascript" src="plugin.js"></script>
</head>
<body>
<p id="demo">HELLO EVERYONE</p>
</body>
</html>