User Tools

Site Tools


java-script:script-tag-placement

This is an old revision of the document!


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:

  • async: Downloads the script asynchronously and executes it as soon as it's available.
  • defer: Downloads the script asynchronously but ensures that it's executed after the HTML has been parsed.

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>.

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.

java-script/script-tag-placement.1691524926.txt.gz · Last modified: 2023/08/08 23:02 by odefta