Performance API
The toJSON() method of the PerformanceContainerTiming interface is a Serialization; it returns a JSON representation of the PerformanceContainerTiming object.
Syntax
toJSON()
Parameters
None.
Return value
A JSON object that is the serialization of the PerformanceContainerTiming object.
The JSON doesn't contain the PerformanceContainerTiming.lastPaintedElement or PerformanceContainerTiming.rootElement properties, because they are of type HTMLElement, which doesn't provide a toJSON() operation.
Examples
Using the toJSON method
This example demonstrates how the toJSON() method is used.
HTML
First we define a section element that is marked as a container root identified as "hero" by its containertiming attribute.
The section contains two other elements that will be drawn, resulting in a container performance entry.
<section containertiming="hero">
<h2>Hero content</h2>
<p>The parent element of this paragraph is a container root.</p>
</section>
Note that there is also hidden HTML (and code) for displaying log information.
<pre id="log"></pre>
#log {
height: 350px;
overflow: scroll;
padding: 0.5rem;
border: 1px solid black;
}
const logElement = document.querySelector("#log");
function log(text) {
logElement.innerText = `${logElement.innerText}${text}\n`;
logElement.scrollTop = logElement.scrollHeight;
}
JavaScript
The following code first checks whether the browser supports "container" entries: if not, it logs that the feature is not supported.
It then creates a PerformanceObserver that logs each entry, calling the toJSON() method directly to get the JSON object.
The observer is then started, filtering only for entries of type "container".
if (PerformanceObserver.supportedEntryTypes.includes("container")) {
const observer = new PerformanceObserver((list) => {
for (const entry of list.getEntries()) {
log(JSON.stringify(entry.toJSON(), null, 2));
}
});
observer.observe({ type: "container", buffered: true });
} else {
log("This feature is not supported by your browser.");
}
Result
The JSON output is displayed in the log that follows the elements.
Using the toJSON method
Note that in this case only one entry is logged, even though the container root has two child elements, because both elements paint in the container's first frame.
The browser emits at most one PerformanceContainerTiming entry for every container root on each rendering frame (aggregating every element that paints during that frame).
The entry should look something like this:
{
"name": "",
"entryType": "container",
"startTime": 77,
"duration": 0,
"identifier": "hero",
"intersectionRect": {
"x": 0,
"y": 19.916666666666668,
"width": 359.7,
"height": 66.71666666666667,
"top": 19.916666666666668,
"right": 359.7,
"bottom": 86.63333333333334,
"left": 0
},
"size": 10519,
"firstRenderTime": 77,
"paintTime": 77,
"presentationTime": null
}
Specifications
Browser compatibility
See also
- JSON
来源:MDN Web Docs / Mozilla 贡献者 · 作者与贡献记录 · CC BY-SA 2.5。离线整理了版式、链接和媒体显示。
