Where should I put <script> tags in HTML markup?
Placing your <script>
tags correctly in an HTML document can make a significant difference in performance and user experience. Below are the most common strategies, along with best practices for modern development.
1. End of the <body>
(Recommended for Most Cases)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>My Page</title> </head> <body> <!-- Page content here --> <!-- Scripts here, just before closing body tag --> <script src="app.js"></script> </body> </html>
Why this is recommended:
- Improved Page Load Performance: The browser can render the page before executing scripts, reducing blocking and improving perceived speed.
- Safe Access to DOM Elements: By the time scripts run, the DOM is fully loaded, reducing the need for
document.ready
or DOM-content-loaded events.
2. In the <head>
with defer
or async
If you must place scripts in the <head>
(e.g., for third-party analytics), you can use either async
or defer
:
<head> <!-- Load script asynchronously --> <script src="analytics.js" async></script> <!-- Load script in order, but defers execution until the document is parsed --> <script src="app.js" defer></script> </head>
Key Differences:
async
: Download and execute the script as soon as it’s available. No guaranteed order relative to other scripts. Best for analytics or scripts that don’t depend on DOM readiness.defer
: Downloads the script in parallel, but execution is deferred until after the HTML is parsed. The browser preserves the order of multiple deferred scripts.
3. Inline Scripts for Immediate Execution
If you have a small piece of code that must run immediately—for example, configuring global variables before other scripts run—you might place it inline in the <head>
:
<head> <script> window.globalConfig = { apiBaseUrl: "https://example.com" }; </script> </head>
Trade-Off:
- It can block rendering, so keep inline scripts short and minimal.
Best Practices
- Load Scripts at the Bottom: Minimize blocking and ensure DOM readiness.
- Use
async
ordefer
: For scripts in the head that don’t need synchronous execution, especially for external resources like analytics. - Bundle and Minify: Combine scripts into fewer files where possible and minify them to reduce load times.
- Avoid Inline Scripts for Large Code: Keep your HTML clean, and let external
.js
files handle the logic unless there’s a clear, immediate need.
Level Up Your JavaScript and Web Development Skills
If you want to deepen your understanding of JavaScript and how to build performant, user-friendly web apps, explore these courses on DesignGurus.io:
They offer practical exercises, pattern-based approaches, and insights into writing efficient, modern JavaScript code. For additional tutorials on coding best practices and system design, check out the DesignGurus.io YouTube channel.