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

浏览器兼容性

另见