Speculation Rules 预渲染与导航性能优化实践概述Speculation Rules 基于声明式策略在可能的导航目标上进行预渲染或预取,适用于菜单、搜索结果等高概率点击场景。策略示例<script type="speculationrules"> { "prerender": [ { "source": "document", "where": { "href_matches": "/products/.*" } } ], "prefetch": [ { "eagerness": "moderate", "where": { "href_matches": "/search\?q=.*" } } ] } </script> 结合事件概率的动态控制// 依据鼠标停留与滚动曝光概率,动态插入/移除规则 function applyRules(json) { const el = document.querySelector('script[type="speculationrules"]'); if (el) el.remove(); const s = document.createElement('script'); s.type = 'speculationrules'; s.textContent = JSON.stringify(json); document.head.appendChild(s); } 验证方法测试环境:Windows 11 / macOS 14;Chrome 121+(预渲染) / Edge 同步;Safari(降级为预取)。指标:对比预渲染命中场景的 `LCP/TTFB`;统计命中率与资源占用。安全边界:避免对含登录态或敏感页面进行预渲染;校验 CSP 配置。兼容性:在不支持的浏览器降级为 `prefetch` 或常规缓存策略。注意事项谨慎选择 `eagerness`,避免带宽浪费与缓存污染。明确身份态与个性化页面禁用预渲染,防止状态泄漏。与路由框架的导航钩子协同,避免双重渲染。

发表评论 取消回复