跳至內容

分析

Next.js 內建支援效能指標的測量和報告功能。您可以使用 useReportWebVitals hook 自行管理報告,或者,Vercel 提供了託管服務,自動為您收集和視覺化指標。

自行建置

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

查看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-hydration:頁面開始和完成注水所需的時間(以毫秒為單位)。
  • Next.js-route-change-to-render:路由變更後頁面開始渲染所需的時間(以毫秒為單位)。
  • Next.js-render:路由變更後頁面完成渲染所需的時間(以毫秒為單位)。

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

export function reportWebVitals(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
  }
}

這些指標適用於所有支援 使用者計時 API 的瀏覽器。

將結果傳送到外部系統

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

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 的資訊。