defer downloads an external classic script without blocking parsing and runs it after parsing; async runs when its download is ready.
HTML script loading: choose ordered defer or independent async work
Use it for a real task
A receipt page needs its UI script after the DOM exists, so it uses defer. A separate analytics script has no dependency on that UI and can use async. This distinction is about execution order, not only speed; an async script can run before or after nearby markup finishes parsing.
<head>
<meta charset="utf-8">
<title>Receipt review</title>
<script src="/assets/receipt-ui.js" defer></script>
<script src="/assets/usage-metrics.js" async></script>
</head>What the markup guarantees
Both paths must point to trusted files owned by the application. A deferred script can still fail to download or throw during execution; ship useful HTML first so the page is readable when behavior is unavailable.
Cost and limits
The HTML stays small while each script adds transfer, parse, and execution cost. A third-party dependency would add an external trust and availability boundary; this example uses only local assets.
Common Mistakes
- Do not rely on async scripts executing in source order.
- defer on an inline classic script does not provide the same external-loading behavior.
- Do not make basic page text appear only after a script runs.
Connected lessons
- HTML document skeleton: declare language, encoding, and a real title
- HTML landmarks: give navigation, main content, and page edges clear owners
- JavaScript Tutorial: Getting Started
Continue with HTML template: stage inert markup before a script clones it.
Related: HTML noscript: keep the essential task available without enhancement.
Related: HTML module scripts: load one module without ordering every classic script.
Related: HTML script data: escape serialized values at the boundary.
Continue with HTML subresource integrity: bind a stylesheet to the bytes you reviewed.
Related CSS decisions
Continue with the connected Web Development lesson: Page loading: keep content available while CSS and scripts arrive.
