跳到內容
API 參考函式useReportWebVitals

useReportWebVitals

useReportWebVitals 這個 Hook 讓您可以回報 Core Web Vitals,並且可以與您的分析服務結合使用。

pages/_app.js
import { useReportWebVitals } from 'next/web-vitals'
 
function MyApp({ Component, pageProps }) {
  useReportWebVitals((metric) => {
    console.log(metric)
  })
 
  return <Component {...pageProps} />
}

useReportWebVitals

作為 Hook 參數傳遞的 metric 物件包含許多屬性

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

Web Vitals

Web Vitals 是一組有用的指標,旨在捕捉網頁的使用者體驗。以下 Web Vitals 都包含在內

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

pages/_app.js
import { useReportWebVitals } from 'next/web-vitals'
 
function MyApp({ Component, pageProps }) {
  useReportWebVitals((metric) => {
    switch (metric.name) {
      case 'FCP': {
        // handle FCP results
      }
      case 'LCP': {
        // handle LCP results
      }
      // ...
    }
  })
 
  return <Component {...pageProps} />
}

自訂指標

除了上面列出的核心指標外,還有一些額外的自訂指標,用於衡量頁面水合和渲染所需的時間

  • Next.js-hydration:頁面開始和完成水合所需的時間長度(以毫秒為單位)
  • Next.js-route-change-to-render:頁面在路由更改後開始渲染所需的時間長度(以毫秒為單位)
  • Next.js-render:頁面在路由更改後完成渲染所需的時間長度(以毫秒為單位)

您可以分別處理所有這些指標的結果

pages/_app.js
import { useReportWebVitals } from 'next/web-vitals'
 
function MyApp({ Component, pageProps }) {
  useReportWebVitals((metric) => {
    switch (metric.name) {
      case 'Next.js-hydration':
        // handle hydration results
        break
      case 'Next.js-route-change-to-render':
        // handle route-change to render results
        break
      case 'Next.js-render':
        // handle render results
        break
      default:
        break
    }
  })
 
  return <Component {...pageProps} />
}

這些指標在所有支援 User Timing API 的瀏覽器中都有效。

在 Vercel 上的使用方式

Vercel Speed Insights 不使用 useReportWebVitals,而是使用 @vercel/speed-insights 套件。useReportWebVitals Hook 在本地開發中很有用,或者如果您使用不同的服務來收集 Web Vitals。

將結果發送到外部系統

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

useReportWebVitals((metric) => {
  const body = JSON.stringify(metric)
  const url = 'https://example.com/analytics'
 
  // Use `navigator.sendBeacon()` if available, falling back to `fetch()`.
  if (navigator.sendBeacon) {
    navigator.sendBeacon(url, body)
  } else {
    fetch(url, { body, method: 'POST', keepalive: true })
  }
})

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

useReportWebVitals(metric => {
  // Use `window.gtag` if you initialized Google Analytics as this example:
  // 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), // values must be integers
    event_label: metric.id, // id unique to current page load
    non_interaction: true, // avoids affecting bounce rate.
  });
}

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