useReportWebVitals

useReportWebVitals 鉤子允許您報告 核心 Web 指標 (Core Web Vitals),並可與您的分析服務結合使用。

傳遞給 useReportWebVitals 的新函式會使用當前可用的指標進行呼叫。為避免報告重複數據,請確保回調函式引用不變更(如下方程式碼範例所示)。

app/_components/web-vitals.js
'use client'

import { useReportWebVitals } from 'next/web-vitals'

const logWebVitals = (metric) => {
  console.log(metric)
}

export function WebVitals() {
  useReportWebVitals(logWebVitals)

  return null
}
app/layout.js
import { WebVitals } from './_components/web-vitals'

export default function Layout({ children }) {
  return (
    <html>
      <body>
        <WebVitals />
        {children}
      </body>
    </html>
  )
}

由於 useReportWebVitals 鉤子需要 'use client' 指令,最有效的方法是建立一個由根佈局導入的獨立元件。這樣可以將客戶端邊界僅限於 WebVitals 元件。

useReportWebVitals

作為鉤子參數傳遞的 metric 物件包含以下屬性:

  • id:當前頁面加載上下文中指標的唯一識別碼
  • name:效能指標的名稱。可能的值包括特定於 Web 應用程式的 Web 指標 名稱(TTFB、FCP、LCP、FID、CLS)
  • delta:指標當前值與先前值的差異。該值通常以毫秒為單位,表示指標值隨時間的變化
  • entries:與指標相關聯的 效能條目 (Performance Entries) 陣列。這些條目提供有關指標相關效能事件的詳細資訊
  • navigationType:指示觸發指標收集的 導航類型。可能的值包括 "navigate""reload""back_forward""prerender"
  • rating:指標值的定性評級,提供效能評估。可能的值為 "good""needs-improvement""poor"。評級通常是通過將指標值與指示可接受或次優效能的預定義閾值進行比較來確定的
  • value:效能條目的實際值或持續時間,通常以毫秒為單位。該值提供指標追蹤的效能方面的定量測量。值的來源取決於所測量的特定指標,可以來自各種 效能 API (Performance API)

Web 指標

Web 指標 (Web Vitals) 是一組有用的指標,旨在捕捉網頁的用戶體驗。包含以下所有 Web 指標:

您可以使用 name 屬性處理這些指標的所有結果。

'use client'

import { useReportWebVitals } from 'next/web-vitals'

type ReportWebVitalsCallback = Parameters<typeof useReportWebVitals>[0]

const handleWebVitals: ReportWebVitalsCallback = (metric) => {
  switch (metric.name) {
    case 'FCP': {
      // 處理 FCP 結果
    }
    case 'LCP': {
      // 處理 LCP 結果
    }
    // ...
  }
}

export function WebVitals() {
  useReportWebVitals(handleWebVitals)
}

將結果發送到外部系統

您可以將結果發送到任何端點以測量和追蹤您網站上的真實用戶效能。例如:

function postWebVitals(metrics) {
  const body = JSON.stringify(metric)
  const url = 'https://example.com/analytics'

  // 如果可用,使用 `navigator.sendBeacon()`,否則回退到 `fetch()`
  if (navigator.sendBeacon) {
    navigator.sendBeacon(url, body)
  } else {
    fetch(url, { body, method: 'POST', keepalive: true })
  }
}

useReportWebVitals(postWebVitals)

須知:如果您使用 Google Analytics,使用 id 值可以讓您手動構建指標分佈(以計算百分位數等)

useReportWebVitals(metric => {
  // 如果您像此範例一樣初始化了 Google Analytics,請使用 `window.gtag`:
  // https://github.com/vercel/next.js/blob/canary/examples/with-google-analytics
  window.gtag('event', metric.name, {
    value: Math.round(metric.name === 'CLS' ? metric.value * 1000 : metric.value), // 值必須為整數
    event_label: metric.id, // 當前頁面加載的唯一 id
    non_interaction: true, // 避免影響跳出率
  });
}

閱讀更多關於 將結果發送到 Google Analytics 的資訊。

On this page