PerformanceServerTiming
注意:此功能在 Web Workers 中可用。
PerformanceServerTiming 接口公开了在 Server-Timing HTTP 头部中随响应一起发送的服务器指标。
此接口仅限于同源策略,但您可以使用 Timing-Allow-Origin 头部来指定允许访问服务器指标的域。请注意,在某些浏览器中,此接口仅在安全上下文 (HTTPS) 中可用。
实例属性
PerformanceServerTiming.description只读-
服务器指定的指标描述的字符串值,或一个空字符串。
PerformanceServerTiming.duration只读-
包含服务器指定的指标持续时间的双精度浮点数,或值为
0.0。 PerformanceServerTiming.name只读-
服务器指定的指标名称的字符串值。
实例方法
PerformanceServerTiming.toJSON()-
返回
PerformanceServerTiming对象的 JSON 表示形式。
示例
给定一个发送 Server-Timing 标头的服务器,例如像这样的 Node.js 服务器
js
const http = require("http");
function requestHandler(request, response) {
const headers = {
"Server-Timing": `
cache;desc="Cache Read";dur=23.2,
db;dur=53,
app;dur=47.2
`.replace(/\n/g, ""),
};
response.writeHead(200, headers);
response.write("");
return setTimeout(() => {
response.end();
}, 1000);
}
http.createServer(requestHandler).listen(3000).on("error", console.error);
现在可以通过 PerformanceResourceTiming.serverTiming 属性从 JavaScript 中观察到 PerformanceServerTiming 条目,它们存在于 navigation 和 resource 条目中。
使用 PerformanceObserver 的示例,它会在 navigation 和 resource 性能条目被记录到浏览器性能时间线上时通知。使用 buffered 选项可以访问观察者创建之前的条目。
js
const observer = new PerformanceObserver((list) => {
list.getEntries().forEach((entry) => {
entry.serverTiming.forEach((serverEntry) => {
console.log(
`${serverEntry.name} (${serverEntry.description}) duration: ${serverEntry.duration}`,
);
// Logs "cache (Cache Read) duration: 23.2"
// Logs "db () duration: 53"
// Logs "app () duration: 47.2"
});
});
});
["navigation", "resource"].forEach((type) =>
observer.observe({ type, buffered: true }),
);
使用 Performance.getEntriesByType() 的示例,它仅显示在调用此方法时存在于浏览器性能时间线中的 navigation 和 resource 性能条目。
js
for (const entryType of ["navigation", "resource"]) {
for (const { name: url, serverTiming } of performance.getEntriesByType(
entryType,
)) {
if (serverTiming) {
for (const { name, description, duration } of serverTiming) {
console.log(`${name} (${description}) duration: ${duration}`);
// Logs "cache (Cache Read) duration: 23.2"
// Logs "db () duration: 53"
// Logs "app () duration: 47.2"
}
}
}
}
规范
| 规范 |
|---|
| 服务器计时 # the-performanceservertiming-interface |
浏览器兼容性
加载中…