跳至內容
API 參考 (API Reference)函式 (Functions)使用網頁效能指標回報 (useReportWebVitals)

使用網頁效能指標回報 (useReportWebVitals)

useReportWebVitals 鉤子允許您回報 核心網頁指標,並且可以與您的分析服務結合使用。

app/_components/web-vitals.js
'use client'
 
import { useReportWebVitals } from 'next/web-vitals'
 
export function WebVitals() {
  useReportWebVitals((metric) => {
    console.log(metric)
  })
}
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:效能指標的名稱。可能的值包括 網頁指標 的名稱(TTFB、FCP、LCP、FID、CLS),這些指標特定於網頁應用程式。
  • delta:指標的當前值與先前值之間的差異。該值通常以毫秒為單位,表示指標值隨時間的變化。
  • entries:與指標相關聯的 效能項目 的陣列。這些項目提供有關與指標相關的效能事件的詳細資訊。
  • navigationType:指示觸發指標收集的 導覽類型。可能的值包括 "navigate""reload""back_forward""prerender"
  • rating:指標值的定性評級,提供效能評估。可能的值為 "good""needs-improvement""poor"。評級通常是透過將指標值與預定義的閾值進行比較來確定的,這些閾值表示可接受或次佳的效能。
  • value:效能條目的實際值或持續時間,通常以毫秒為單位。此值提供了由指標追蹤的效能方面的量化衡量。值的來源取決於正在測量的特定指標,並且可以來自各種效能 API

Web Vitals

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

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

app/components/web-vitals.tsx
'use client'
 
import { useReportWebVitals } from 'next/web-vitals'
 
export function WebVitals() {
  useReportWebVitals((metric) => {
    switch (metric.name) {
      case 'FCP': {
        // handle FCP results
      }
      case 'LCP': {
        // handle LCP results
      }
      // ...
    }
  })
}

在 Vercel 上的使用

Vercel 速度洞察 並未使用 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 的資訊。