Where to Place <script> Tags?

The placement of script tags in HTML affects how and when JavaScript code is loaded and executed relative to HTML parsing and rendering.

Traditional Approach

Scripts were traditionally placed at the end of the <body> tag to prevent blocking HTML parsing and rendering. This ensures the DOM is fully loaded before script execution.

<!DOCTYPE html>
<html>
<head>
<title>My Page</title>
</head>
<body>
<h1>Welcome</h1>
<!-- Script at end of body -->
<script src="app.js"></script>
</body>
</html>

Modern Approach with Attributes

With modern JavaScript, scripts can be placed in the <head> using async or defer attributes for non-blocking loading:

  • async: Downloads script asynchronously and executes it as soon as it’s available, potentially before DOM is fully loaded.
  • defer: Downloads script asynchronously but waits until HTML parsing is complete before execution, maintaining script order.
<!DOCTYPE html>
<html>
<head>
<title>My Page</title>
<script src="app.js" defer></script>
<script src="analytics.js" async></script>
</head>
<body>
<h1>Welcome</h1>
</body>
</html>

Key Considerations

PlacementProsCons
End of BodyDOM ready, simpleDelayed loading
Head with deferOrder preserved, non-blockingSlightly complex
Head with asyncFastest loadingUnpredictable order

Best Practices:

  • Use defer for external scripts that need DOM access or execution order
  • Use async for independent scripts (e.g., analytics)
  • Place critical scripts at body end if attributes aren’t an option

Note: In React applications, script management is often handled through bundlers like Webpack or Vite, reducing the need for manual script tag placement.