The LargestContentfulPaint interface provides timing information about the largest image or text paint before user input on a web page.
Description
The key moment this API provides is the Largest Contentful Paint (LCP) metric. It provides the render time of the largest image or text block visible within the viewport, recorded from when the page first begins to load. The following elements are considered when determining the LCP:
The time the element was rendered to the screen. May not be available if the element is a cross-origin image loaded without the Timing-Allow-Origin header.
Returns a JSON representation of the LargestContentfulPaint object.
Examples
Observing the largest contentful paint
In the following example, an observer is registered to get the largest contentful paint while the page is loading. The buffered flag is used to access data from before observer creation.
The LCP API analyzes all content it finds (including content that is removed from the DOM). When new largest content is found, it creates a new entry. It stops searching for larger content when scroll or input events occur, since these events likely introduce new content on the website. Thus the LCP is the last performance entry reported by the observer.
js
const observer =newPerformanceObserver((list)=>{const entries = list.getEntries();const lastEntry = entries[entries.length -1];// Use the latest LCP candidate
console.log("LCP:", lastEntry.startTime);
console.log(lastEntry);});
observer.observe({type:"largest-contentful-paint",buffered:true});
Cross-origin image render time
For security reasons, the value of the renderTime property is 0 if the resource is a cross-origin request. Instead the loadTime is exposed. To expose cross-origin render time information, the Timing-Allow-Origin HTTP response header needs to be set.
For example, to allow https://developer.mozilla.org to see renderTime, the cross-origin resource should send:
http
Timing-Allow-Origin:https://developer.mozilla.org
Like in the code example, you can use startTime, which returns the value of the entry's renderTime if it is not 0, and otherwise the value of this entry's loadTime. However, it is recommended to set the Timing-Allow-Origin header so that the metrics will be more accurate.
If you use startTime, you can flag any inaccuracies by checking if renderTime was used: