PerformanceElementTiming: toJSON() 方法

可用性有限

此特性不是基線特性,因為它在一些最廣泛使用的瀏覽器中不起作用。

實驗性: 這是一項實驗性技術
在生產中使用此技術之前,請仔細檢查瀏覽器相容性表格

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

語法

js
toJSON()

引數

無。

返回值

一個 JSON 物件,它是 PerformanceElementTiming 物件的序列化結果。

JSON 中不包含 element 屬性,因為它屬於 Element 型別,該型別不提供 toJSON() 操作。但會提供元素的 id

示例

使用 toJSON 方法

在此示例中,呼叫 entry.toJSON() 會返回 PerformanceElementTiming 物件的 JSON 表示形式,其中包含有關影像元素的資訊。

html
<img
  src="image.jpg"
  alt="a nice image"
  elementtiming="big-image"
  id="myImage" />
js
const observer = new PerformanceObserver((list) => {
  list.getEntries().forEach((entry) => {
    if (entry.identifier === "big-image") {
      console.log(entry.toJSON());
    }
  });
});
observer.observe({ type: "element", buffered: true });

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

json
{
  "name": "image-paint",
  "entryType": "element",
  "startTime": 670894.1000000238,
  "duration": 0,
  "renderTime": 0,
  "loadTime": 670894.1000000238,
  "intersectionRect": {
    "x": 299,
    "y": 76,
    "width": 135,
    "height": 155,
    "top": 76,
    "right": 434,
    "bottom": 231,
    "left": 299
  },
  "identifier": "big-image",
  "naturalWidth": 135,
  "naturalHeight": 155,
  "id": "myImage",
  "url": "https://en.wikipedia.org/static/images/project-logos/enwiki.png"
}

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

規範

規範
Element Timing API
# dom-performanceelementtiming-tojson

瀏覽器相容性

另見