Script Loading Strategies
How to use async and defer attributes to optimize script loading and prevent render-blocking.
What it is
Script Loading Strategies determine how the browser downloads and executes JavaScript files in relation to HTML parsing. There are three main approaches:
1. **Synchronous (Default)**: The browser stops HTML parsing, downloads the script, executes it, and then resumes parsing.
2. **Async**: The browser downloads the script in the background while parsing HTML. As soon as the download finishes, it pauses parsing to execute the script.
3. **Defer**: The browser downloads the script in the background while parsing HTML. It waits until HTML parsing is 100% complete before executing the script.
Why it matters
Optimizing script loading is crucial for a fast First Contentful Paint (FCP).
Synchronous scripts cause the 'white screen of death' by blocking the main thread.
Understanding async and defer allows you to download scripts early without halting the rendering process, while ensuring that dependent scripts execute in the correct order.
How it works (The Timeline)
**Sync:** Parse HTML 🛑 → Download → Execute → Resume Parse HTML
**Async:** Parse HTML (while Download in parallel) 🛑 → Execute (as soon as downloaded) → Resume Parse HTML
**Defer:** Parse HTML (while Download in parallel) ✅ → Finish Parse HTML → Execute (in exact document order)
Try it
Watch the Construction Site Race Track. See how a bulldozer (HTML Parser) reacts to delivery trucks (Scripts) depending on the loading strategy.
Check yourself
Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.
Remember this
- Default scripts block parsing AND downloading.
- Async scripts download in parallel but block parsing to execute immediately.
- Defer scripts download in parallel and wait for parsing to finish before executing.
- Defer guarantees execution order. Async does not.
Done with this concept?
Mark it complete to track your progress. No login needed.