沙箱环境里performance.getentriesbytype('resource')常返回空数组,主因是沙箱默认禁用资源时序采集:iframe需显式添加allow-performance权限,跨域资源缺timing-allow-origin头会被过滤,动态插入资源在load前未完成加载;应改用buffered:true的performanceobserver实时捕获。

为什么沙箱环境里 performance.getEntriesByType('resource') 常返回空数组
因为沙箱(如 iframe sandbox="allow-scripts"、Web Worker、或某些微前端隔离容器)默认禁用 Performance API 的资源时序采集能力,或者资源条目被丢弃。即使脚本能执行,performance.getEntriesByType('resource') 也可能返回空数组——不是没加载,而是浏览器根本没记录。
关键限制点有三个:
- iframe 沙箱必须显式添加
allow-performance权限(Chrome 98+ 支持,Firefox 尚未实现),否则所有 PerformanceEntry 都不可见 - 资源若跨域且服务端未返回
Timing-Allow-Origin头,字段全为 0 或缺失,沙箱下更敏感,常直接过滤掉整条 entry - 动态插入的资源(如
document.createElement('script').src = url后 append)在沙箱中可能因策略延迟触发加载,导致window.addEventListener('load', ...)回调时它还没完成,自然进不了 entries
如何在沙箱内正确捕获 resource 条目
不能依赖 load 事件后一次性取数,得用 PerformanceObserver 并启用 buffered: true,确保历史条目不丢失。但注意:沙箱 iframe 内的 observer 只能监听自身上下文的资源,无法看到父页面的。
实操写法:
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 });
重点检查:
- 是否在沙箱 iframe 的
<iframe sandbox="allow-scripts allow-performance"></iframe>中声明了权限 - 第三方脚本域名是否在服务端响应头中设置了
Timing-Allow-Origin: https://your-sandbox-domain.com - 避免在沙箱内用
eval()或new Function()加载脚本——这类资源 initiatorType 为undefined,只能靠entry.name.includes(...)匹配
沙箱中 DNS/TCP 耗时异常高的典型原因
沙箱环境本身不增加网络耗时,但会放大已有配置问题。比如:
- DNS 查询慢(
domainLookupEnd - domainLookupStart > 100ms):沙箱 iframe 通常复用父页面的 DNS 缓存;若父页未访问过该域名,沙箱首次解析就会卡住,且无法预连接(rel="preconnect"在沙箱内无效) - TCP 连接慢(
connectEnd - connectStart > 200ms):沙箱不继承父页面的已建立连接池,每次都要新建 TCP 连接,尤其 HTTPS 下 TLS 握手开销翻倍 - TTFB 高但 responseEnd - responseStart 很小:说明后端处理慢,而沙箱请求常被识别为“非主文档请求”,CDN 或网关可能降低其调度优先级
验证方式:对比同一脚本在沙箱内外的 entry.secureConnectionStart 是否为 0 —— 若沙箱内为 0,说明 TLS 握手未被记录,大概率是跨域头缺失或沙箱策略拦截。
容易被忽略的沙箱性能盲区
Resource Timing 只管网络阶段,沙箱里真正拖慢体验的,往往是那些「不发请求却卡主线程」的操作:
- 沙箱 iframe 内运行的 JS,若含大量同步 DOM 操作或未节流的 resize 监听器,会阻塞父页面渲染,但
performance.getEntriesByType('resource')完全看不到 - 微前端场景下,子应用通过
import-html-entry注入 script,其initiatorType是html而非script,常规 filter 会漏掉 - 沙箱中
fetch()请求的 resource entry,initiatorType是fetch,但若用了credentials: 'include'且跨域,Timing-Allow-Origin必须精确匹配协议+域名+端口,少一个都归零
所以别只盯着 resource duration,沙箱性能瓶颈往往藏在 longtask 和 layout shift 里——得配 PerformanceObserver 监听 longtask 和 layout-shift 才算完整。
大量免费API接口:立即使用
涵盖生活服务API、金融科技API、企业工商API、等相关的API接口服务。免费API接口可安全、合规地连接上下游,为数据API应用能力赋能!











