What are the async
and defer
Attributes in the <script>
Tag?
When loading JavaScript in an HTML document using the <script>
tag, the async
and defer
attributes control how the script is downloaded and executed.
1. Default Behavior (Without async
or defer
):
htmlCopyEdit<script src="script.js"></script>
- The script is downloaded and executed immediately when the browser encounters it.
- HTML parsing is paused until the script is fully loaded and executed.
- Can block page rendering if the script is large or slow to load.
2. async
Attribute:
htmlCopyEdit<script src="script.js" async></script>
How async
Works:
- Script is downloaded in parallel with HTML parsing.
- Once downloaded, the script is executed immediately, pausing HTML parsing.
- Scripts with
async
are executed as soon as they are ready, regardless of their order in the document.
Best For:
- Independent scripts that don’t depend on other scripts or DOM content.
- Tracking scripts, analytics, or ads.
Key Points:
✅ Non-blocking download.
⏸️ Blocking execution (pauses HTML parsing when it runs).
❌ Execution order is not guaranteed (e.g., if multiple async scripts are present).
3. defer
Attribute:
htmlCopyEdit<script src="script.js" defer></script>
How defer
Works:
- Script is downloaded in parallel with HTML parsing.
- Execution is deferred until after the entire HTML document is parsed.
- Scripts with
defer
are executed in the order they appear in the document.
Best For:
- Scripts that depend on the DOM being fully loaded.
- When you have multiple scripts that should run in sequence.
Key Points:
✅ Non-blocking download.
✅ Non-blocking execution (executed after the HTML parsing is done).
✅ Execution order is guaranteed.
4. Comparison Table:
Attribute | Download Time | Execution Time | Blocks HTML Parsing? | Execution Order |
---|---|---|---|---|
None | When encountered | Immediately after download | Yes | In document order |
async | Parallel with HTML parsing | Immediately when ready | Yes (pauses parsing) | Random (depends on download speed) |
defer | Parallel with HTML parsing | After HTML is fully parsed | No | In document order |
5. Which One Should You Use?
✅ Use defer
for most scripts that rely on DOM content (e.g., application logic).
✅ Use async
for scripts that don’t depend on other scripts or DOM (e.g., analytics, ads).
❌ Avoid blocking scripts (no async
or defer
) unless necessary.
6. Example Usage:
htmlCopyEdit<!-- Async: Good for Analytics -->
<script src="analytics.js" async></script>
<!-- Defer: Good for Application Logic -->
<script src="app.js" defer></script>
<script src="helper.js" defer></script>
Using defer
is generally the safest and most efficient choice for scripts that manipulate the DOM or depend on other scripts.