Table of Contents

Script tag placement

The <script> tag can be placed in both the <head> and <body> sections of an HTML document, and the location can affect how the script is executed.

Placing the Script in the Head

Traditionally, scripts were often placed in the <head> section. However, this can block the rendering of the page until the script is downloaded and executed, leading to slower page load times, especially if the script is large or the network is slow.

To avoid blocking, you can use the async or defer attributes:

Example:

<head>
  <script src="myscript.js" defer></script>
</head>

Placing the Script in the Body

Placing the <script> tag at the end of the <body> section has become a common practice to improve page loading performance. By placing the script at the end of the body, you ensure that the HTML content is loaded and displayed to the user before the script is downloaded and executed.

Example:

<body>
  <!-- HTML content here -->
  <script src="myscript.js"></script>
</body>

This approach helps prevent the script from blocking the rendering of the page, similar to using the defer attribute in the <head>.

Async vs Defer

Both the async and defer attributes are used with the <script> tag to control how external JavaScript files are loaded and executed in an HTML document. They affect the loading behavior of scripts to help optimize page rendering, but they work slightly differently.

Async

Example:

<script async src="myscript.js"></script>

Defer

Example:

<script defer src="myscript.js"></script>

Comparison

Use async when the script is completely independent, and it doesn't matter when it runs. Since it runs as soon as it's downloaded, it can interfere with page rendering if it's a large script or if there's a slow network.

Use defer when you need the script to run after the HTML is parsed, or when you have multiple scripts that need to be run in a specific order. Since it waits for the HTML to be parsed, it is often more user-friendly as it doesn't block rendering.

Both async and defer only apply to external scripts (those loaded with the src attribute). If the script is inline (i.e., the code is contained directly within the <script> tags), these attributes have no effect. Additionally, these attributes are supported in HTML5, so they should be used with caution if you need to support very old browsers.

Conclusion

If the script must be executed as soon as possible, and you're using modern attributes like async or defer, placing it in the <head> is fine.

If the script doesn't need to run until the page's content is loaded, placing it at the end of the <body> can be a better choice to improve loading performance.