分析
Next.js 內建支援測量與回報效能指標。您可以使用 useReportWebVitals
鉤子自行管理回報,或者 Vercel 提供 託管服務 來自動收集並視覺化指標。
自行建置
'use client'
import { useReportWebVitals } from 'next/web-vitals'
export function WebVitals() {
useReportWebVitals((metric) => {
console.log(metric)
})
}
import { WebVitals } from './_components/web-vitals'
export default function Layout({ children }) {
return (
<html>
<body>
<WebVitals />
{children}
</body>
</html>
)
}
由於
useReportWebVitals
鉤子需要"use client"
指令,效能最佳的做法是建立一個獨立的元件,並由根佈局導入。這樣可以將客戶端邊界限制在WebVitals
元件內。
查看 API 參考文件 以取得更多資訊。
Web 核心指標
Web 核心指標 是一組實用的指標,旨在捕捉網頁的使用者體驗。以下指標均包含在內:
您可以使用 name
屬性來處理這些指標的所有結果。
'use client'
import { useReportWebVitals } from 'next/web-vitals'
export function WebVitals() {
useReportWebVitals((metric) => {
switch (metric.name) {
case 'FCP': {
// 處理 FCP 結果
}
case 'LCP': {
// 處理 LCP 結果
}
// ...
}
})
}
'use client'
import { useReportWebVitals } from 'next/web-vitals'
export function WebVitals() {
useReportWebVitals((metric) => {
switch (metric.name) {
case 'FCP': {
// 處理 FCP 結果
}
case 'LCP': {
// 處理 LCP 結果
}
// ...
}
})
}
將結果傳送至外部系統
您可以將結果傳送至任何端點,以測量與追蹤網站上的真實使用者效能。例如:
useReportWebVitals((metric) => {
const body = JSON.stringify(metric)
const url = 'https://example.com/analytics'
// 優先使用 `navigator.sendBeacon()`,若不可用則降級為 `fetch()`
if (navigator.sendBeacon) {
navigator.sendBeacon(url, body)
} else {
fetch(url, { body, method: 'POST', keepalive: true })
}
})
須知:如果您使用 Google Analytics,利用
id
值可以手動建構指標分佈 (用於計算百分位數等)
useReportWebVitals((metric) => { // 若您已初始化 Google Analytics 如本例,請使用 `window.gtag`: // https://github.com/vercel/next.js/blob/canary/examples/with-google-analytics/pages/_app.js window.gtag('event', metric.name, { value: Math.round( metric.name === 'CLS' ? metric.value * 1000 : metric.value ), // 值必須為整數 event_label: metric.id, // 當前頁面載入的唯一識別碼 non_interaction: true, // 避免影響跳出率 }) })
閱讀更多關於 將結果傳送至 Google Analytics 的資訊。