LargestContentfulPaint

可用性有限

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

LargestContentfulPaint 介面提供有關網頁上使用者輸入前最大的影像或文字繪製的計時資訊。

描述

此 API 提供的關鍵時刻是 Largest Contentful Paint (LCP) 指標。它提供了視口內最大的可見影像或文字塊的渲染時間,該時間從頁面開始載入時開始記錄。確定 LCP 時會考慮以下元素:

  • <img> 元素。
  • SVG 中的 <image> 元素。
  • <video> 元素的 poster 影像。
  • 具有 background-image 的元素。
  • 文字節點組,例如 <p>

要測量其他元素的渲染時間,請使用 PerformanceElementTiming API。

PerformancePaintTiming API 提供了其他關鍵的繪製時刻。

  • 首次繪製 (FP):任何內容被渲染的時間。請注意,首次繪製的標記是可選的,並非所有使用者代理都報告它。
  • 首次內容繪製 (FCP):第一個 DOM 文字或影像內容被渲染的時間。

LargestContentfulPaint 繼承自 PerformanceEntry

PerformanceEntry LargestContentfulPaint

要準確測量跨域資源的渲染時間,請設定 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 是觀察器報告的最後一個性能條目。

js
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

瀏覽器相容性

另見