PerformanceResourceTiming: encodedBodySize 属性
注意:此功能在 Web Workers 中可用。
encodedBodySize 只读属性表示在移除任何应用的 Content-Encoding(例如 gzip 或 Brotli)之前,从 fetch(HTTP 或缓存)接收到的有效负载主体的大小(以字节为单位)。如果资源是从应用程序缓存或本地资源检索的,则必须返回移除任何应用的 Content-Encoding 之前的有效负载主体的大小。
值
encodedBodySize 属性可以具有以下值
- 一个数字,表示在移除任何应用的 Content-Encoding 之前,从 fetch(HTTP 或缓存)接收到的有效负载主体的大小(以字节为单位)。
- 如果资源是跨域请求且未使用
Timing-Allow-OriginHTTP 响应头,则返回0。
示例
检查内容是否被压缩
如果 encodedBodySize 和 decodedBodySize 属性是非空的且不相等,则表示内容被压缩了(例如,gzip 或 Brotli)。
使用 PerformanceObserver 的示例,它会在浏览器性能时间线中记录新的 resource 性能条目时通知。使用 buffered 选项可以访问观察者创建之前的条目。
js
const observer = new PerformanceObserver((list) => {
list.getEntries().forEach((entry) => {
const uncompressed =
entry.decodedBodySize && entry.decodedBodySize === entry.encodedBodySize;
if (uncompressed) {
console.log(`${entry.name} was not compressed!`);
}
});
});
observer.observe({ type: "resource", buffered: true });
使用 Performance.getEntriesByType() 的示例,它只显示在调用此方法时浏览器性能时间线中存在的 resource 性能条目
js
const resources = performance.getEntriesByType("resource");
resources.forEach((entry) => {
const uncompressed =
entry.decodedBodySize && entry.decodedBodySize === entry.encodedBodySize;
if (uncompressed) {
console.log(`${entry.name} was not compressed!`);
}
});
跨域内容大小信息
如果 encodedBodySize 属性的值为 0,则该资源可能是跨域请求。要公开跨域内容大小信息,需要设置 Timing-Allow-Origin HTTP 响应头。
例如,要允许 https://mdn.org.cn 查看内容大小,跨域资源应发送
http
Timing-Allow-Origin: https://mdn.org.cn
规范
| 规范 |
|---|
| 资源时序 # dom-performanceresourcetiming-encodedbodysize |
浏览器兼容性
加载中…