On this article, we’re going to study that what are the explanations that we should always not add the <script> tag on the high of the physique tag contained in the HTML code as an alternative of that we should always add the script file on the finish of the HTML code.
There are two approaches for including the script file within the HTML which are:
1. TOP Method: Within the high method we are going to add the script file both within the head tag or on the high of the physique tag.
- First Method within the head tag
<html> <head> <script src="https://www.geeksforgeeks.org/where-should-we-use-script-tag-in-the-html/path/filename.js"></script> </head> <physique> ... </physique> </html>
- Second Method on the high of the physique tag
Instance: So, we will likely be understanding with the assistance of an implementation utilizing the second method as defined under:
Drawback of the TOP Method:
- As we will see that we’re getting no alert if we’re clicking the button as a result of after the physique tag the script tag has loaded and contained in the script tag there’s an occasion listener that has been utilized on the button that has not been created until now as we will see within the under DOM tree for extra rationalization.
In order that’s why we should always not add the script tag on the high of the physique tag as you’ll be able to see above. It’s a main drawback of including the script file on the high of the HTML.
2. END Method: Ultimately method we will likely be utilizing the script tag on the backside of the physique tag:
Instance: Let’s perceive the Finish Method with the assistance of an implementation as defined under:
Benefits of the END Method:
- Through the use of the Finish Method you’ll not get any error within the JS code on the console of the browser and all of the factor tags are discovered by the DOM API that’s current within the HTML code.