PerformanceServerTiming: toJSON() 方法

Baseline 已广泛支持

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

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

PerformanceServerTiming 接口的 toJSON() 方法是一个序列化器;它返回 PerformanceServerTiming 对象的 JSON 表示形式。

语法

js
toJSON()

参数

无。

返回值

一个 PerformanceServerTiming 对象的序列化后的 JSON 对象。

示例

记录服务器计时条目

服务器计时指标需要服务器发送 Server-Timing 标头。例如:

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

serverTiming 条目可以存在于 navigationresource 条目上。

使用 PerformanceObserver 的示例,它会在 navigationresource 性能条目被记录到浏览器性能时间线上时通知。使用 buffered 选项可以访问观察者创建之前的条目。

js
const observer = new PerformanceObserver((list) => {
  list.getEntries().forEach((entry) => {
    entry.serverTiming.forEach((serverEntry) => {
      console.log(serverEntry.toJSON());
    });
  });
});

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

这将记录一个类似如下的 JSON 对象

json
{
  "name": "cache",
  "duration": 23.2,
  "description": "Cache Read"
}

要获取 JSON 字符串,您可以直接使用 JSON.stringify(serverEntry);它会自动调用 toJSON()

规范

规范
服务器计时
# dom-performanceservertiming-tojson

浏览器兼容性