Always place the scripts at the bottom of the HTML

Always place the scripts at the bottom of the HTML

Technically, the <script> tag can be placed inside two places of an HTML Document:

  1. Inside the <head> tag, that is, at the beginning of the HTML document.
  2. Before the closing </body> tag, that is, At the end of the HTML document.

Inside the <head> tag: This causes a pretty bad user experience for the website visitors

<html lang="en">
<head>
    <title>Homepage</title>
    <script src="js/main.js"></script>
</head>
<body>
    ...
</body>
</html>

This is not a good practice because:

  1. Javascript is render-blocking
  2. The HTML elements are loaded after the javascript code is executed. So, if the javascript code is trying to select any HTML element, it wouldn't find it and ends up throwing a "reference not found" error. Don't worry about this yet! We will discuss this in detail a bit later.

Render blocking means that whenever the browser comes across the Javascript code, it will stop rendering the rest of the page until the Javascript code is fully executed.

This will result in a blank page for the website visitors if a particular piece of Javascript code is located at the top of the HTML document or if the code is taking a long time to get executed.

This is better show than explained.

Come on, go ahead and visit the example page of "Render Blocking Javascript".

If you open the above page, you won't see the main content unless the popup is closed:

This is because the javascript code for the popup is placed before the main content of the page.

This will force the browser to render the main content only after it has dealt with the popup.

Trust me, this is more than a common scenario.

And this causes a pretty bad user experience for the website visitors.

<html lang="en">
<head>
    ...
</head>
<body>
    <p>Some HTML Content</p>
    <script src="js/main.js"></script>
</body>
</html>

If you notice the above snippet, The <script> tag is placed just before the closing </body> tag.

Having said that, if it is absolutely necessary for you to include the Javascript inside the <head> tag, then add async attribute to the <script> tag.

For example:

<head>
    <title>Homepage</title>
    <script src="js/main.js" async></script>
</head>

The async attribute will tell the browser not to block the rendering of the page, and the execution of the code will get delayed until most of the page rendering is done.

It is almost the same as adding the <script> tag at the bottom of the HTML.

We will learn more about the asynchronous nature of Javascript in the "Asynchronous Javascript" module.

Anyway, now that we understand how to set up our Javascript code inside the HTML, let's perform a small task in the next lesson.