In the HTML document, the <script> tag can be placed in different positions, depending on when you want the script to execute. Generally, there are two primary positions: the <head> section and the end of the <body> section.
-
Placing the
<script>tag within the<head>: Placing the<script>tag within the<head>means it loads and executes before the rest of the page content is loaded. The benefit is that it ensures the JavaScript code loads before the DOM is constructed, which is suitable for scripts that do not depend on DOM elements or need to execute early, such as configuration files or character set settings.However, this approach may slow down page loading because the browser parses and executes the JavaScript in the
<head>first, which can delay the display of page content.For example, configuring the page's character set:
html<head> <meta charset="UTF-8"> <script> // Configuration information or scripts not dependent on other page elements </script> </head> -
Placing the
<script>tag at the end of the<body>: Placing the<script>tag at the end of the<body>tag, typically just before the closing</body>tag, executes the JavaScript after the HTML document's elements have been parsed. This is currently the most common and recommended approach because it allows the browser to load the page content first, enabling users to view the webpage sooner and enhancing user experience.This approach ensures that the DOM is fully constructed when the script executes, allowing safe DOM manipulation. It also reduces the visible rendering time.
For example, when the page is nearly loaded, adding interactive features:
html<body> <!-- Page content --> <script> // Scripts that depend on DOM elements, such as event listeners and DOM operations </script> </body>
In some cases, you may also see the <script> tag used with the async or defer attributes, which allow for finer control over the loading and execution timing of scripts:
-
The
asyncattribute indicates that the script is asynchronously loaded and executes immediately once downloaded, without waiting for other scripts or the HTML document parsing to complete. It is suitable for scripts that do not depend on other page scripts or the completion of DOM content loading.html<script async src="script.js"></script> -
The
deferattribute indicates that the script executes after the HTML document parsing is complete but before theDOMContentLoadedevent is triggered. It is suitable for scripts that need to access the DOM but do not affect the initial rendering of the document.html<script defer src="script.js"></script>
Based on practical development experience, unless there are specific requirements, it is generally recommended to place JavaScript scripts containing actual functionality at the bottom of the <body> tag to improve page loading performance and user experience.