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.

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.

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)