跳至內容

分析

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

建構您自己的

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 hook 需要 "use client" 指令,效能最佳的做法是建立一個根佈局匯入的獨立組件。這將客戶端邊界完全限制在 WebVitals 組件內。

檢視API 參考以取得更多資訊。

網頁重要指標

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

您可以使用 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
      }
      // ...
    }
  })
}

將結果傳送到外部系統

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

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