How it works
The HTML Standard's prepare the script element algorithm runs when the parser finishes a <script> end tag, or when script connects a script element to the document. For an external classic script or any module script, it files the element in one of four places on the document:
- Set of scripts that will execute as soon as possible: elements with
async, or with the force async flag. Each runs whenever its fetch completes.
- List of scripts that will execute in order as soon as possible: script-inserted elements without async. Each runs once it and everything before it are ready.
- List of scripts that will execute when the document has finished parsing: parser-inserted
defer and non-async module scripts.
- Pending parsing-blocking script: everything else that the parser created. The parser stops until it runs.
An inline classic script skips all of this and runs at once, unless a style sheet is blocking scripts; then it becomes the pending parsing-blocking script.
Force async is why injected scripts are async. Elements created by the parser start with it false; elements created by script start with it true. The async getter returns true when either force async or the content attribute is set, and the setter clears force async, which moves the element from set 1 to list 2.
When parsing stops, the end runs: it sets readyState to "interactive", runs list 3 in order (each waiting for its fetch and for blocking style sheets), queues DOMContentLoaded, then waits for sets 1 and 2 to empty and for everything delaying the load event before firing load.
Inline module scripts still go through a queued networking task even with no imports, so they never run synchronously the way inline classic scripts do.
Edge cases
Script-inserted scripts, served with the same delays:
const ran = [];
window.log = (name) => ran.push(name);
const add = (name, delay, inOrder) => {
const script = document.createElement('script');
if (inOrder) script.async = false;
script.src = `/js?name=${name}&delay=${delay}`;
document.head.append(script);
};
console.log(document.createElement('script').async);
// → true
add('a1', 300); add('a2', 0); // default: run on arrival
add('o1', 300, true); add('o2', 0, true); // async = false: insertion order
addEventListener('load', () => {
console.log(ran.filter((name) => name.startsWith('a')).join(', '));
// → a2, a1
console.log(ran.filter((name) => name.startsWith('o')).join(', '));
// → o1, o2
});
Chrome 156 and Firefox 159 agreed in three loads each. How the two groups interleave differed between the browsers, which is allowed: only the order inside the ordered list is guaranteed.
- Async before
DOMContentLoaded. With two parser-inserted async scripts (300 ms and 0 ms) and a 600 ms defer script, both browsers ran the fast async, the slow async, the deferred script, then DOMContentLoaded. Make the deferred script fast and the async ones run after it.
document.write() and the ignore-destructive-writes counter. Executing an external script or any module increments the document's counter. document.write() with no parser insertion point returns early when the counter is above zero; without it, it would call document.open() and replace the document. Chrome 156 logged its warning for the module case too.
currentScript. It points to the running classic <script>, but is null while a module runs; modules use import.meta.url.
- Modules run once. Two
<script type="module"> elements importing the same URL share one module instance from the module map, so its top-level code runs once.
Real-world scenario
A page loads vendor.js, app.js that uses it, and an analytics tag, all with async to "make the page faster". Whenever the smaller app.js arrives first, it throws a ReferenceError, so the bug shows up only on some loads and networks. The fix: defer on vendor.js and app.js (or one module graph with import), keep async only on the independent analytics tag. If the analytics vendor's snippet still uses document.write(), loading it asynchronously silently drops the write, which is why such snippets were rewritten to inject elements.
Trade-offs
Parser-blocking scripts give a guarantee nothing else does: they run before any later markup is parsed, which document.write() and early feature detection rely on. The cost is a stalled parser for every round trip. defer and modules keep the parser moving and preserve order, but nothing runs until parsing ends, so a huge HTML document delays the app. async runs earliest but gives up order and any guarantee about the DOM being complete.