跳至內容
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)。
  • delta:指標的當前值與先前值之間的差值。該值通常以毫秒為單位,表示指標值隨時間的變化。
  • entries:與指標相關聯的 效能項目 (Performance Entries) 的陣列。這些項目提供了與指標相關的效能事件的詳細資訊。
  • navigationType:指示觸發指標收集的 導覽類型。可能的值包括 "navigate""reload""back_forward""prerender"
  • rating:指標值的定性評級,提供效能評估。可能的值為 "good""needs-improvement""poor"。評級通常是通過將指標值與預定義的閾值進行比較來確定的,這些閾值指示可接受或次佳的效能。
  • value:效能項目的實際值或持續時間,通常以毫秒為單位。該值提供了指標所追蹤的效能方面的量化衡量。值的來源取決於正在測量的特定指標,並且可以來自各種 效能 API (Performance API)

網頁重要指標

網頁重要指標 是一組實用的指標,旨在捕捉網頁的使用者體驗。以下網頁重要指標皆包含在內:

您可以使用 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 頁面水合作用時間:頁面開始和完成水合作用所需的時間(以毫秒為單位)
  • Next.js 路由變更到渲染時間:路由變更後頁面開始渲染所需的時間(以毫秒為單位)
  • Next.js 渲染時間:路由變更後頁面完成渲染所需的時間(以毫秒為單位)

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

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} />
}

這些指標適用於所有支援 使用者計時 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