The placement of script tags in HTML affects how and when JavaScript code is loaded and executed relative to HTML parsing and rendering.
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>
With modern JavaScript, scripts can be placed in the <head>
using async
or defer
attributes for non-blocking loading:
<!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>
Placement | Pros | Cons |
---|---|---|
End of Body | DOM ready, simple | Delayed loading |
Head with defer | Order preserved, non-blocking | Slightly complex |
Head with async | Fastest loading | Unpredictable order |
Best Practices:
defer
for external scripts that need DOM access or execution orderasync
for independent scripts (e.g., analytics)Note: In React applications, script management is often handled through bundlers like Webpack or Vite, reducing the need for manual script tag placement.