async vs defer Attributes
What you'll learn: How async and defer control when external scripts download and execute, preventing blocking and ensuring proper timing.
When you add a <script src="..."> tag to your HTML, the browser normally stops parsing, downloads the script, executes it immediately, then continues parsing. This blocks rendering and slows down your page.
The async and defer attributes change this behavior.
How async Works
The async attribute tells the browser: "Download this script in the background while parsing HTML, and execute it as soon as it's ready."
- Downloads in parallel (non-blocking)
- Executes immediately when download completes (interrupts parsing)
- No guaranteed order if multiple async scripts exist
- Best for independent scripts like analytics that don't depend on DOM or other scripts
<script src="analytics.js" async></script>
How defer Works
The defer attribute tells the browser: "Download in the background, but wait until HTML parsing is complete before executing."
- Downloads in parallel (non-blocking)
- Executes after parsing finishes, before
DOMContentLoaded - Preserves order — multiple defer scripts run sequentially
- Best for DOM-dependent scripts or scripts that must run in order
<script src="library.js" defer></script>
<script src="app.js" defer></script>
<!-- library.js always runs before app.js -->
Analogy
Think of downloading groceries:
- Normal script: Stop everything, go to store, buy items, cook immediately, then resume your day
- async: Order delivery, continue your day, cook the moment it arrives (even mid-task)
- defer: Order delivery, continue your day, cook only after you finish all your tasks
Key Takeaway: Use async for independent scripts that can run anytime; use defer for scripts that need the DOM ready or must execute in a specific order.