How Defer Scripts Execute Relative to HTML Parsing
The defer attribute in HTML <script>
tags instructs the browser to download JavaScript files asynchronously
in the background while continuing to parse the HTML document. Unlike
standard scripts that block document parsing, deferred scripts do not
interrupt the construction of the Document Object Model (DOM). This
article explains the lifecycle of a defer script, covering
its parallel download, execution timing immediately after parsing
finishes, and the preservation of script execution order.
Asynchronous Downloading During HTML Parsing
When a browser encounters a standard
<script src="..."> tag without attributes, it
immediately pauses HTML parsing to fetch and execute the script file.
When the defer attribute is added
(<script src="..." defer>), the browser initiates the
network request to download the script file in parallel on a background
thread. The HTML parser continues reading the document and building the
DOM tree without any interruption or render-blocking delay.
Execution After HTML Parsing Completes
Although downloading occurs concurrently with parsing, the execution
of deferred scripts is strictly delayed. The browser will never execute
a defer script while the HTML parser is actively building
the DOM. Execution only begins once the browser reaches the end of the
HTML document and the DOM is fully constructed.
Firing Before DOMContentLoaded
Deferred scripts execute immediately after HTML parsing is complete,
but strictly before the DOMContentLoaded event is
dispatched. The browser guarantees that all deferred scripts have run to
completion before triggering DOMContentLoaded. This ensures
that any event listeners or initializations set up inside a deferred
script are established before DOM-ready callbacks fire.
Preserving Script Execution Order
Unlike the async attribute, which executes scripts as
soon as they finish downloading regardless of document structure,
defer guarantees execution order. If multiple
<script defer> elements are placed in an HTML
document, the browser will execute them sequentially based on their
relative order in the markup, even if a later script finishes
downloading first.
Summary of the Execution Lifecycle
- Discovery: The HTML parser encounters
<script defer src="...">. - Download: The script downloads in the background while HTML parsing continues.
- Parsing Complete: The browser finishes constructing the full DOM tree.
- Execution: Deferred scripts execute sequentially in the exact order they appear in the HTML.
- Event Trigger: The browser dispatches the
DOMContentLoadedevent.