PerformanceServerTiming

Baseline 已广泛支持

此功能已成熟,并可在许多设备和浏览器版本上运行。自 2023 年 3 月以来,它已在各种浏览器中可用。

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

安全上下文: 此功能仅在安全上下文(HTTPS)中可用,且支持此功能的浏览器数量有限。

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 条目,它们存在于 navigationresource 条目中。

使用 PerformanceObserver 的示例,它会在 navigationresource 性能条目被记录到浏览器性能时间线上时通知。使用 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() 的示例,它仅显示在调用此方法时存在于浏览器性能时间线中的 navigationresource 性能条目。

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

浏览器兼容性

另见