Difference: defer vs async?
Both defer and async download an external script in parallel without blocking HTML parsing. A defer script runs after the whole document has been parsed, just before DOMContentLoaded, and deferred scripts run in document order. An async script runs as soon as it finishes downloading, which can interrupt parsing, and async scripts run in whatever order they arrive.
Timeline
- No attribute: parse, stop, download, execute, continue parsing.
async: parse while downloading, stop briefly to execute when ready, continue.defer: parse while downloading, finish parsing, then execute in order.
When to use which
defer | async | |
|---|---|---|
| Execution time | after parsing, before DOMContentLoaded | as soon as downloaded |
| Order | preserved | not guaranteed |
| DOM available | yes, fully parsed | maybe not |
| Good for | app code, scripts that depend on each other or on the DOM | independent scripts: analytics, ads, widgets |
Modules
<script type="module"> behaves like defer by default. <script type="module" async> runs as soon as the module and its imports are ready.
Notes
- Both only apply to external scripts with
src(exceptasyncon modules, which also works inline). - Scripts inserted dynamically with JavaScript are async by default.
DOMContentLoadedwaits for deferred scripts but not for async ones.- With both attributes, modern browsers use
async.
Performance
Putting defer scripts in <head> lets the browser discover and download them early while still not blocking rendering, which is better than placing classic scripts at the end of <body>.
Code example
1<p>Open the console and reload to see execution order.</p>23<!-- Simulated scripts using data URLs so the demo is self-contained -->4<script defer src="data:text/javascript,console.log('defer 1: runs after parsing, in order')"></script>5<script defer src="data:text/javascript,console.log('defer 2: always after defer 1')"></script>6<script async src="data:text/javascript,console.log('async: runs whenever it is ready')"></script>78<script>9 console.log("inline classic: runs immediately while parsing");10 document.addEventListener("DOMContentLoaded", () => {11 console.log("DOMContentLoaded: after deferred scripts");12 });13</script>1415<!-- Typical real-world usage:16<script src="/js/app.js" defer></script>17<script src="https://analytics.example.com/script.js" async></script>18-->19<p>Last element in the document.</p>
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the HTML & CSS set.