Speculative Parsing and Preload Scanner
Browsers run a lightweight speculative parser ahead of the main one to discover subresources early, but scripts and DOM mutations can invalidate its assumptions.
Definition
Speculative parsing is the browser's technique of scanning the incoming HTML with a secondary, fast parser to find and start fetching resources before the primary parser reaches them.
Context and scope
It explains why subresources sometimes load before scripts and why a parser-blocking script can delay discovery of later assets.
Common misconceptions
- the speculative scanner executes scripts it finds
- the preload scanner always matches what the DOM will contain
Anti-patterns
- injecting critical resources only from JavaScript
- depending on document.write to add resources
Related concepts
Authoritative source
https://developer.mozilla.org/en-US/docs/Glossary/speculative_parsing
Definition
Speculative parsing is the browser’s technique of scanning the incoming HTML with a secondary, fast parser to find and start fetching resources before the primary parser reaches them.
It explains why subresources sometimes load before scripts and why a parser-blocking script can delay discovery of later assets. Compared to simpler alternatives, this concept fits best when the trade-off it represents is the one the system actually cares about.
When to use it
A common use case is applying it at the boundary where the cost of getting it wrong is highest, and the scenario usually involves a concrete guarantee the system must uphold. Unlike an ad hoc approach, it makes that guarantee explicit, reviewable, and testable.
How it works
The preload scanner looks only at raw markup, so resources created dynamically by scripts are invisible to it and start late.
document.write and write-injected markup can force the scanner’s discovered resources to be discarded, which is one reason the API is discouraged.
Trade-offs and alternatives
Serve critical scripts without blocking discovery and avoid hiding important resources behind script execution so the scanner can fetch them as early as possible. The main drawback is the extra complexity it introduces, so the benefit should clearly outweigh that cost before a team adopts it.
Common misconceptions
A persistent misconception is that the speculative scanner executes scripts it finds. Another is that the preload scanner always matches what the DOM will contain. For example, an engineer who assumes otherwise may design around a guarantee that does not actually exist, which only becomes obvious under load or failure.
Anti-patterns to avoid
Two recurring anti-patterns are to injecting critical resources only from JavaScript and to depending on document.write to add resources. Both tend to surface as hard-to-debug production issues rather than obvious test failures. Related concepts include Render-Blocking Resources, Native ES Modules in the Browser, Import Maps for Module Resolution.