Script Loading Strategies: async vs defer
You'll learn how async and defer attributes control when scripts download, parse, and execute—and how each affects page rendering.
When you add a <script> tag to HTML, the browser typically stops parsing the page, downloads the script, executes it, then resumes. This blocks rendering and slows down your page.
The Problem with Regular Scripts
<script src="app.js"></script>
This halts HTML parsing until app.js downloads and runs. If it's a large file or slow network, users see a blank screen.
The defer Attribute
<script src="app.js" defer></script>
Think of defer as "download in the background, but wait politely."
- Downloads while HTML parsing continues (non-blocking)
- Executes after the entire HTML is parsed, but before
DOMContentLoaded - Scripts run in the order they appear
- Perfect for scripts that need the full DOM available
The async Attribute
<script src="analytics.js" async></script>
Think of async as "download and run ASAP, order doesn't matter."
- Downloads while HTML parsing continues
- Executes immediately when downloaded, pausing HTML parsing
- Scripts run in unpredictable order
- Best for independent scripts (analytics, ads) that don't depend on DOM or other scripts
When to Use Which
defer: Your main app logic, scripts needing DOM access, scripts with dependenciesasync: Third-party analytics, social widgets, ads—anything standalone- Neither: Only for critical inline scripts needed before rendering
Key Takeaway: Use defer for order-dependent scripts that need the DOM; use async for independent third-party scripts. Both prevent render-blocking by allowing parallel downloads.