How Async and Defer Alter JavaScript Loading
When browsers encounter a standard <script> tag,
HTML parsing pauses while the script is downloaded and executed, often
leading to slower page load times. The async and
defer attributes optimize web performance by allowing
external JavaScript files to download in the background without blocking
the HTML parser. While both attributes prevent download-related render
blocking, they differ fundamentally in when the scripts execute and
whether the document maintains the original execution order.
Default Script Loading
Without any attributes, a standard
<script src="script.js"></script> halts HTML
parsing immediately upon discovery. The browser must wait for the script
to download over the network and finish executing before resuming the
construction of the Document Object Model (DOM). This behavior can cause
noticeable delays, especially when scripts are placed in the
<head> section.
The defer Attribute
Adding defer to a script tag
(<script src="script.js" defer></script>)
instructs the browser to download the file in the background while
continuing to parse the HTML document.
- Execution Timing: Deferred scripts execute only
after the entire HTML document has been fully parsed, right before the
DOMContentLoadedevent fires. - Execution Order: Scripts with
deferexecute in the exact order they appear in the HTML markup, regardless of which file finishes downloading first. - Best Use Cases: Use
deferfor scripts that interact with or manipulate the DOM, or for scripts that depend on other scripts (such as a framework and its plugins).
The async Attribute
Adding async
(<script src="script.js" async></script>) also
downloads the script asynchronously without pausing HTML parsing.
However, its execution behavior is independent of both the HTML parser
and other scripts.
- Execution Timing: An
asyncscript executes immediately after it finishes downloading. The HTML parser is paused during the execution phase. - Execution Order: Scripts with
asyncdo not guarantee any execution order. Whichever script finishes downloading first will execute first (“first-come, first-served”). - Best Use Cases: Use
asyncfor completely independent scripts that do not rely on the DOM or other scripts, such as analytics trackers, independent widgets, or advertising tags.
Summary Comparison
| Feature | Default (<script>) |
defer |
async |
|---|---|---|---|
| Download Behavior | Blocks HTML parsing | Non-blocking (background) | Non-blocking (background) |
| Execution Timing | Immediately after download (blocks parsing) | After HTML parsing completes | Immediately after download (blocks parsing) |
| Execution Order | Sequential (as defined) | Guaranteed order (as defined) | Unordered (based on download speed) |
| DOM Dependency | Safe if placed at bottom of
<body> |
Safe (waits for DOM ready) | Unsafe (may run before DOM is parsed) |