useReportWebVitals
useReportWebVitals
這個 Hook 讓您可以回報 Core Web Vitals,並且可以與您的分析服務搭配使用。
app/_components/web-vitals.js
'use client'
import { useReportWebVitals } from 'next/web-vitals'
export function WebVitals() {
useReportWebVitals((metric) => {
console.log(metric)
})
return null
}
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
元件內。
useReportWebVitals
作為 Hook 引數傳遞的 metric
物件包含許多屬性
id
:目前頁面載入情境中指標的唯一識別碼name
:效能指標的名稱。可能的值包括特定於 Web 應用程式的 Web Vitals 指標名稱 (TTFB、FCP、LCP、FID、CLS)。delta
:指標目前值與先前值之間的差異。該值通常以毫秒為單位,表示指標值隨時間的變化。entries
:與指標相關聯的 Performance Entries 陣列。這些條目提供有關與指標相關的效能事件的詳細資訊。navigationType
:指出觸發指標收集的導航類型。可能的值包括"navigate"
、"reload"
、"back_forward"
和"prerender"
。rating
:指標值的定性評級,提供效能評估。可能的值為"good"
、"needs-improvement"
和"poor"
。評級通常是通過將指標值與預定義的閾值進行比較來確定的,這些閾值指示可接受或次佳的效能。value
:效能條目的實際值或持續時間,通常以毫秒為單位。該值提供了由指標追蹤的效能方面的定量度量。值的來源取決於正在測量的特定指標,並且可能來自各種 Performance API。
Web Vitals
Web Vitals 是一組旨在捕捉網頁使用者體驗的實用指標。以下包含所有 Web Vitals:
- Time to First Byte (TTFB)
- First Contentful Paint (FCP)
- Largest Contentful Paint (LCP)
- First Input Delay (FID)
- Cumulative Layout Shift (CLS)
- Interaction to Next Paint (INP)
您可以使用 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 Speed Insights 並未使用 useReportWebVitals
,而是使用 @vercel/speed-insights
套件。如果您在本地開發,或使用不同的服務來收集 Web Vitals,useReportWebVitals
Hook 會很有用。
將結果傳送到外部系統
您可以將結果傳送到任何端點,以衡量和追蹤您網站上的真實使用者效能。例如
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 的資訊。
這有幫助嗎?