useReportWebVitals Hook 允许你上报 核心 Web Vitals,并可与你的分析服务结合使用。
传递给 useReportWebVitals 的新函数会在达到该时间点时的可用指标时被调用。为防止上报重复数据,请确保回调函数的引用不发生改变(如下面的代码示例所示)。
import { useReportWebVitals } from 'next/web-vitals'
const logWebVitals = (metric) => {
console.log(metric)
}
function MyApp({ Component, pageProps }) {
useReportWebVitals(logWebVitals)
return <Component {...pageProps} />
}'use client'
import { useReportWebVitals } from 'next/web-vitals'
const logWebVitals = (metric) => {
console.log(metric)
}
export function WebVitals() {
useReportWebVitals(logWebVitals)
return null
}import { WebVitals } from './_components/web-vitals'
export default function Layout({ children }) {
return (
<html>
<body>
<WebVitals />
{children}
</body>
</html>
)
}由于
useReportWebVitalsHook 需要'use client'指令,因此最有效能的方法是创建一个单独的组件,并由根布局导入。这会将客户端边界(client boundary)仅限于WebVitals组件。
作为 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: 性能条目的实际值或持续时间,通常以毫秒为单位。该值提供了跟踪性能方面的定量度量。该值的来源取决于所测量的具体指标,并且可以来自各种 性能 API (Performance API)。Web Vitals 是一组有用的指标,旨在捕捉网页的用户体验。以下 Web Vitals 都已包含在内:
你可以使用 name 属性处理这些指标的所有结果。
import { useReportWebVitals } from 'next/web-vitals'
const handleWebVitals = (metric) => {
switch (metric.name) {
case 'FCP': {
// handle FCP results
}
case 'LCP': {
// handle LCP results
}
// ...
}
}
function MyApp({ Component, pageProps }) {
useReportWebVitals(handleWebVitals)
return <Component {...pageProps} />
}'use client'
import { useReportWebVitals } from 'next/web-vitals'
type ReportWebVitalsCallback = Parameters<typeof useReportWebVitals>[0]
const handleWebVitals: ReportWebVitalsCallback = (metric) => {
switch (metric.name) {
case 'FCP': {
// handle FCP results
}
case 'LCP': {
// handle LCP results
}
// ...
}
}
export function WebVitals() {
useReportWebVitals(handleWebVitals)
}'use client'
import { useReportWebVitals } from 'next/web-vitals'
const handleWebVitals = (metric) => {
switch (metric.name) {
case 'FCP': {
// handle FCP results
}
case 'LCP': {
// handle LCP results
}
// ...
}
}
export function WebVitals() {
useReportWebVitals(handleWebVitals)
}除了上面列出的核心指标外,还有一些额外的自定义指标,用于测量页面水合和渲染所需的时间:
Next.js-hydration: 页面开始和完成水合所需的时间(以毫秒为单位)Next.js-route-change-to-render: 路由更改后页面开始渲染所需的时间(以毫秒为单位)Next.js-render: 路由更改后页面完成渲染所需的时间(以毫秒为单位)你可以单独处理这些指标的所有结果:
import { useReportWebVitals } from 'next/web-vitals'
function handleCustomMetrics(metrics) {
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
}
}
function MyApp({ Component, pageProps }) {
useReportWebVitals(handleCustomMetrics)
return <Component {...pageProps} />
}这些指标在所有支持 用户计时 API (User Timing API) 的浏览器中都有效。
你可以将结果发送到任何端点,以测量和跟踪你网站上的真实用户性能。例如:
function postWebVitals(metrics) {
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 })
}
}
useReportWebVitals(postWebVitals)值得注意: 如果你使用 Google Analytics,使用
id值可以让你手动构建指标分布(例如计算百分位数等)。
javascriptuseReportWebVitals(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 的信息。