Where should we use script tag in the HTML ?
In this article, we are going to learn about that what are the reasons that we should not add the <script> tag at the top of the body tag inside the HTML code instead of that we should add the script file at the end of the HTML code.
There are two approaches for adding the script file in the HTML that are:
- TOP Approach
- END Approach
1. TOP Approach: In the top approach we will add the script file either in the head tag or at the top of the body tag.
- First Approach in the head tag
<html> <head> <script src="path/filename.js"></script> </head> <body> ... </body> </html>
- Second Approach at the top of the body tag
Example: So, we will be understanding with the help of an implementation using the second approach as explained below:
Disadvantage of the TOP Approach:
- As we can see that we are getting no alert if we are clicking the button because after the body tag the script tag has loaded and inside the script tag there is an event listener that has been applied on the button that has not been created till now as we can see in the below DOM tree for more explanation.
So that’s why we should not add the script tag at the top of the body tag as you can see above. It is a major disadvantage of adding the script file at the top of the HTML.
2. END Approach: In the end approach we will be using the script tag at the bottom of the body tag:
Example: Let’s understand the End Approach with the help of an implementation as explained below:
Advantages of the END Approach:
- By using the End Approach you will not get any error in the JS code on the console of the browser and all the element tags are found by the DOM API that is present in the HTML code.
Please Login to comment...