LargestContentfulPaint
LargestContentfulPaint 接口提供有关网页上用户输入前最大的图像或文本绘制的计时信息。
描述
此 API 提供的关键时刻是 Largest Contentful Paint (LCP) 指标。它提供了视口内最大的可见图像或文本块的渲染时间,该时间从页面开始加载时开始记录。确定 LCP 时会考虑以下元素:
<img>元素。- SVG 中的
<image>元素。 <video>元素的 poster 图像。- 具有
background-image的元素。 - 文本节点组,例如
<p>。
要测量其他元素的渲染时间,请使用 PerformanceElementTiming API。
PerformancePaintTiming API 提供了其他关键的绘制时刻。
LargestContentfulPaint 继承自 PerformanceEntry。
要准确测量跨域资源的渲染时间,请设置 Timing-Allow-Origin 标头。
开发人员应使用 startTime 而不是 renderTime 作为 LCP 值,因为 renderTime 在某些浏览器中可能未设置。
有关更多详细信息,请参阅 跨域图像渲染时间 和 使用 startTime 而非 renderTime。
实例属性
此接口通过对以下属性进行限定和约束来扩展 PerformanceEntry 属性:
PerformanceEntry.entryType只读 实验性-
返回
"largest-contentful-paint"。 PerformanceEntry.name只读 实验性-
始终返回空字符串。
PerformanceEntry.startTime只读 实验性-
如果此条目的
renderTime不为0,则返回其renderTime值,否则返回其loadTime值。 PerformanceEntry.duration只读 实验性-
返回
0,因为duration不适用于此接口。
它还支持以下属性:
LargestContentfulPaint.element只读-
当前最大的内容绘制的元素。
LargestContentfulPaint.renderTime只读-
元素渲染到屏幕的时间。如果元素是未通过
Timing-Allow-Origin标头加载的跨域图像,则该值可能是粗略值或0。 LargestContentfulPaint.loadTime只读-
元素加载的时间。
LargestContentfulPaint.size只读-
元素返回的固有尺寸,表示为面积(宽度 * 高度)。
LargestContentfulPaint.id只读-
元素的 ID。当没有 ID 时,此属性返回空字符串。
LargestContentfulPaint.url只读-
如果元素是图像,则为图像的请求 URL。
实例方法
此接口还继承了 PerformanceEntry 的方法。
LargestContentfulPaint.toJSON()-
返回
LargestContentfulPaint对象的 JSON 表示。
示例
观察最大的内容绘制
在下面的示例中,注册了一个观察器以在页面加载期间获取最大的内容绘制。buffered 标志用于访问观察器创建之前的数据。
LCP API 会分析其找到的所有内容(包括从 DOM 中删除的内容)。当找到新的最大内容时,它会创建一个新的条目。当发生滚动或输入事件时,它会停止搜索更大的内容,因为这些事件可能会引入网站上的新内容。因此,LCP 是观察器报告的最后一个性能条目。
const observer = new PerformanceObserver((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 });
规范
| 规范 |
|---|
| 最大内容绘制 # sec-largest-contentful-paint-interface |
浏览器兼容性
加载中…