因为沙箱默认禁用资源时序采集,需显式添加allow-performance权限、服务端配置timing-allow-origin头、用buffered:true的performanceobserver实时捕获,否则返回空数组。

为什么 performance.getEntriesByType('resource') 在沙箱里常返回空数组
因为沙箱环境(如 <iframe sandbox="allow-scripts"></iframe>)默认不采集资源时序数据,不是代码写错了,是浏览器策略直接屏蔽了入口。
关键限制有三点:
-
iframe必须显式加allow-performance权限(Chrome 98+ 支持,Firefox 不支持) - 跨域资源没配
Timing-Allow-Origin响应头,整条 entry 会被丢弃,不是字段为 0,是压根不进列表 - 动态插入的资源(比如
document.createElement('script').src = url)在window.addEventListener('load', ...)时可能还没完成加载,自然查不到
如何用 PerformanceObserver 捕获沙箱内真实 resource 条目
不能等 load 事件再调一次 getEntriesByType,得用 PerformanceObserver 实时监听,并开启 buffered: true 回溯已加载项。
实操要点:
- observer 只能捕获当前 iframe 上下文内的资源,父页面资源不可见
- 必须在沙箱 iframe 的标签里声明
sandbox="allow-scripts allow-performance" - 第三方域名服务端要返回
Timing-Allow-Origin: https://your-sandbox-domain.com,不能只写*(生产环境需精确) - 避免用
eval()或new Function()加载脚本——这类执行不会生成resource条目
const observer = new PerformanceObserver((list) => {
list.getEntries().forEach(entry => {
if (entry.entryType === 'resource' && entry.initiatorType === 'script') {
console.log(entry.name, {
dns: entry.domainLookupEnd - entry.domainLookupStart,
tcp: entry.connectEnd - entry.connectStart,
ttfb: entry.responseStart - entry.requestStart,
download: entry.responseEnd - entry.responseStart
});
}
});
});
observer.observe({ entryTypes: ['resource'], buffered: true });
怎么区分“页面资源加载耗时”和单个资源耗时对不上的问题
顶部显示的“资源加载 3500ms”不是所有资源耗时之和,而是从 domContentLoadedEventEnd 到 loadEventStart 的墙钟时间——即浏览器认定“所有子资源都该收尾了”的那段空白等待期。
它和 performance.getEntriesByType('resource') 返回的单个资源耗时完全不是同一统计口径:
- 前者来自
performance.timing,是导航级时间戳,精度高、不可篡改 - 后者来自
PerformanceObserver或getEntriesByType,只记录已触发load或error的资源,且会过滤掉fetch/xmlhttprequest - 如果页面里有大量图片懒加载、
iframe异步插入、或资源因重定向/缓存跳过某些阶段,这个差值就会明显拉大
跨域资源字段全为 0 怎么判断是不是 Timing-Allow-Origin 没配
只要看到 domainLookupStart === 0 且 connectStart === 0,基本就能断定是跨域资源缺头——不是 DNS 或 TCP 真快,是浏览器主动抹掉了数据。
验证方式很直接:
- 打开 Chrome DevTools → Network → 点开对应资源 → 查看 Response Headers 里有没有
Timing-Allow-Origin - 如果域名匹配但字段仍为 0,检查是否用了 HTTPS 但证书链不完整(OCSP stapling 失败会导致整个 timing 数据被清空)
- 注意:即使配了头,若资源本身被强缓存(
cache-control: max-age=31536000),DNS/TCP 阶段也会是 0,这是正常行为,不代表配置失败
沙箱环境下 Resource Timing 最容易被忽略的点,不是语法或调用时机,而是权限声明和服务端响应头的配合——少一个,整条链路就断在源头。
大量免费API接口:立即使用
涵盖生活服务API、金融科技API、企业工商API、等相关的API接口服务。免费API接口可安全、合规地连接上下游,为数据API应用能力赋能!











