PerformanceResourceTiming: serverTiming 屬性

Baseline 已廣泛支援

此功能已成熟,並可在許多裝置和瀏覽器版本上執行。自 2023 年 3 月以來,它已在各種瀏覽器中可用。

注意:此功能在 Web Workers 中可用。

安全上下文: 此功能僅在安全上下文(HTTPS)中可用,且支援此功能的瀏覽器數量有限。

只讀屬性 serverTiming 返回一個包含伺服器計時指標的 PerformanceServerTiming 條目陣列。

伺服器計時指標需要伺服器傳送 Server-Timing 標頭。例如:

http
Server-Timing: cache;desc="Cache Read";dur=23.2

serverTiming 條目可以存在於 navigationresource 條目上。

一個 PerformanceServerTiming 條目陣列。

示例

記錄伺服器計時條目

您可以使用 PerformanceObserver 來觀察 PerformanceServerTiming 條目。每個伺服器條目的持續時間將被記錄到控制檯。

使用 PerformanceObserver 的示例,它會在瀏覽器效能時間線中記錄新的 resource 效能條目時通知。使用 buffered 選項可以訪問觀察者建立之前的條目。

js
const observer = new PerformanceObserver((list) => {
  list.getEntries().forEach((entry) => {
    entry.serverTiming.forEach((serverEntry) => {
      console.log(`${serverEntry.name} duration: ${serverEntry.duration}`);
    });
  });
});

["navigation", "resource"].forEach((type) =>
  observer.observe({ type, buffered: true }),
);

使用 Performance.getEntriesByType() 的示例,它只顯示在呼叫此方法時瀏覽器效能時間線中存在的 resource 效能條目

js
for (const entryType of ["navigation", "resource"]) {
  for (const { name: url, serverTiming } of performance.getEntriesByType(
    entryType,
  )) {
    if (serverTiming) {
      for (const { name, duration } of serverTiming) {
        console.log(`${url}: ${name} duration: ${duration}`);
      }
    }
  }
}

跨域伺服器計時資訊

對伺服器計時資訊的訪問僅限於同源。要公開跨域計時資訊,需要設定 Timing-Allow-Origin HTTP 響應標頭。

例如,要允許 https://mdn.club.tw 檢視伺服器計時資訊,跨域資源應傳送:

http
Timing-Allow-Origin: https://mdn.club.tw

規範

規範
伺服器計時
# servertiming-attribute

瀏覽器相容性

另見