<script>
is used to execute JavaScript code in the HTML document.
You can include it in the <head>
or the <body>
tag or in both places.
This thread explains the various ways you can use the script tag and how you should use it depending on your use case.
The most common way to use the script tag is to include it right before the closing </body>
tag. Why?
Two reasons
- It blocks the HTML parsing when it is executing the javascript code inside it. So if you place it before, the HTML has to wait until the execution is complete.
- It does not have a reference of the HTML elements after it. So if you query for an element defined after the script tag closes it will come out as undefined.
There are three ways to use the script tag
<script>
<script defer>
<script async>
<script>
This is the usual way to use it. You can add javascript code directly inside the tag or include an src attribute to link to an external javascript file that has to be downloaded. It immediately executes the code upon download. Until the download and execution are complete the HTML parsing is blocked. So you might not see the HTML page until the execution of the code is complete
<script defer>
This is a better way to link external javascript files than as compared to defining it before </body>
because
- it downloads the javascript file WITHOUT blocking the parsing of HTML
- the javascript code executes only after the HTML parsing is complete
- Suppose you have a really long HTML file, the browser does not have to wait for the javascript file to download after the first paint because it has already been downloaded. This gives the feeling of the page being faster
<script async>
This is similar to defer because it also downloads the JavaScript file without blocking the HTML parsing. However, the JavaScript code executes immediately after the download which does BLOCKS the HTML parsing.
The below image illustrates the visual representation of how they work.
credits: growingwiththeweb.com
Thank you for reading! Post your comments or questions down below!๐