PerformanceResourceTiming: toJSON() 方法

Baseline 已廣泛支援

此功能已非常成熟,可在多種裝置和瀏覽器版本上使用。自 2017 年 10 月以來,它已在各大瀏覽器中可用。

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

toJSON() 方法是 PerformanceResourceTiming 介面的一個 序列化器;它返回 PerformanceResourceTiming 物件的 JSON 表示形式。

語法

js
toJSON()

引數

無。

返回值

一個 JSON 物件,表示 PerformanceResourceTiming 物件的序列化結果。

示例

使用 toJSON 方法

在此示例中,呼叫 entry.toJSON() 會返回 PerformanceResourceTiming 物件的 JSON 表示形式。

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

observer.observe({ type: "resource", buffered: true });

這將記錄一個類似如下的 JSON 物件

json
{
  "name": "https://upload.wikimedia.org/wikipedia/en/thumb/4/4a/Commons-logo.svg/31px-Commons-logo.svg.png",
  "entryType": "resource",
  "startTime": 110.80000001192093,
  "duration": 11.599999994039536,
  "initiatorType": "img",
  "nextHopProtocol": "h2",
  "renderBlockingStatus": "non-blocking",
  "workerStart": 0,
  "redirectStart": 0,
  "redirectEnd": 0,
  "fetchStart": 110.80000001192093,
  "domainLookupStart": 110.80000001192093,
  "domainLookupEnd": 110.80000001192093,
  "connectStart": 110.80000001192093,
  "connectEnd": 110.80000001192093,
  "secureConnectionStart": 110.80000001192093,
  "requestStart": 117.30000001192093,
  "responseStart": 120.40000000596046,
  "responseStatus": 200,
  "responseEnd": 122.40000000596046,
  "transferSize": 0,
  "encodedBodySize": 880,
  "decodedBodySize": 880,
  "serverTiming": [
    {
      "name": "cache",
      "duration": 0,
      "description": "hit-front"
    },
    {
      "name": "host",
      "duration": 0,
      "description": "cp3061"
    }
  ]
}

要獲取 JSON 字串,您可以直接使用 JSON.stringify(entry);它會自動呼叫 toJSON()

規範

規範
資源時序
# dom-performanceresourcetiming-tojson

瀏覽器相容性

另見