概念概述
推测性解析与预加载扫描器(Speculative Parsing and Preload Scanner)指的是:浏览器在主解析器之前用轻量推测解析器提前发现并抓取子资源,但脚本与 DOM 变更可能使其假设失效,导致资源延迟加载。
从更严格的定义看,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. 它与 Render-Blocking Resources、Native ES Modules in the Browser、Import Maps for Module Resolution 等概念经常一起出现,用于解决相近的工程问题。理解它的适用场景,有助于在多种备选方案之间做出有依据的取舍,而不是凭直觉选择技术方案。
常见误解
- the speculative scanner executes scripts it finds
- the preload scanner always matches what the DOM will contain
需要避免的反模式
- injecting critical resources only from JavaScript
- depending on document.write to add resources
实践要点
- 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.
- Serve critical scripts without blocking discovery and avoid hiding important resources behind script execution so the scanner can fetch them as early as possible.
参考来源
https://developer.mozilla.org/en-US/docs/Glossary/speculative_parsing