HTMLIntermediate
What is the difference between async and defer in <script>?
Background: Why Do We Need async / defer?
When the browser encounters a <script> tag during HTML parsing, it stops parsing, downloads and executes the JS, then resumes — this can slow down page load. Both async and defer allow JS to download asynchronously, but they differ in when execution happens.
Three Loading Approaches
<!-- Normal (blocking) -->
<script src="app.js"></script>
<!-- async -->
<script src="app.js" async></script>
<!-- defer -->
<script src="app.js" defer></script>
Execution Timeline
Normal: HTML parsing ----[pause]---- [download+execute JS] ---- resume HTML
async: HTML parsing ==parallel download== [execute immediately] ---- resume HTML
defer: HTML parsing ==parallel download== ---- HTML done ---- [execute JS]
Key Differences
| Attribute | Download | Execution | Preserves Order |
|---|---|---|---|
| None | Blocks, immediate | Immediately after download | ✅ |
async |
Parallel with HTML | Immediately after download | ❌ |
defer |
Parallel with HTML | After HTML parsing completes, in order | ✅ |
When to Use Each
defer: Best for most cases, especially scripts that manipulate the DOM or depend on other scriptsasync: Best for independent scripts that don't rely on DOM or other scripts (e.g., Google Analytics)- No attribute: Avoid unless the script must execute immediately and blocking is acceptable
✦ AI Mock Interview
Type your answer and get instant AI feedback
Sign in to use AI scoring
