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 |
瀏覽器相容性
載入中…