Async
and defer
in JavaScript Script Tags
When adding JavaScript files to an HTML document using the <script>
tag, async
and defer
control how and when the script is downloaded and executed.
1. Default Behavior (Without async
or defer
)
🔹 The browser stops parsing HTML when it encounters this script, downloads and executes it immediately, then continues rendering the rest of the page.
🔹 This can block the page from rendering if the script takes time to load.
2. async
Attribute
🔹 The script downloads in parallel while the HTML continues to be parsed.
🔹 Once downloaded, the script executes immediately, pausing HTML parsing.
🔹 Best for: Independent scripts that don’t depend on other scripts (e.g., analytics, ads).
Example Use Case:
✅ Good for scripts that don’t modify the DOM or rely on other scripts.
3. defer
Attribute
🔹 The script downloads in parallel while the HTML is being parsed.
🔹 The script executes only after the entire HTML document is loaded.
🔹 Best for: Scripts that depend on the full DOM structure (e.g., adding event listeners).
Example Use Case:
✅ Ensures main.js
executes only after the page is fully loaded.
4. Key Differences:
Attribute | Download | Execution | Blocks HTML Parsing? | Order of Execution |
---|---|---|---|---|
❌ None | Immediately | Immediately | ✅ Yes | In order of appearance |
✅ async | In parallel | Immediately after download | ❌ No | Order is unpredictable |
✅ defer | In parallel | After the HTML is fully parsed | ❌ No | In order of appearance |
5. When to Use Which?
Use Case | Best Option |
---|---|
Analytics, tracking scripts | async |
DOM-dependent scripts (e.g., event listeners, UI updates) | defer |
Scripts that modify the page immediately (jQuery, inline scripts) | No attribute |
Multiple scripts that need to run in order | defer |
6. Best Practice for Performance
For better performance and non-blocking execution, place scripts at the end of <body>
or use defer
:
Conclusion
- Use
async
when script execution order doesn't matter (e.g., analytics, ads). - Use
defer
when scripts depend on the full DOM and need to run in order. - Avoid blocking scripts without
async
defer
unless necessary.
Would you like an example of using these in a real project?