跳到主要内容

useReportWebVitals

useReportWebVitals 钩子允许你报告 核心 Web 指标,并可以与你的分析服务结合使用。

传递给 useReportWebVitals 的新函数会使用到该点为止的可用指标进行调用。为了防止报告重复数据,确保回调函数引用不会改变(如下面的代码示例所示)。

pages/_app.js
import { useReportWebVitals } from 'next/web-vitals'

const logWebVitals = (metric) => {
console.log(metric)
}

function MyApp({ Component, pageProps }) {
useReportWebVitals(logWebVitals)

return <Component {...pageProps} />
}
app/_components/web-vitals.js
'use client'

import { useReportWebVitals } from 'next/web-vitals'

const logWebVitals = (metric) => {
console.log(metric)
}

export function WebVitals() {
useReportWebVitals(logWebVitals)

return null
}
app/layout.js
import { WebVitals } from './_components/web-vitals'

export default function Layout({ children }) {
return (
<html>
<body>
<WebVitals />
{children}
</body>
</html>
)
}

由于 useReportWebVitals 钩子需要 'use client' 指令,最高效的方法是创建一个根布局导入的单独组件。这会将客户端边界限制在 WebVitals 组件内。

useReportWebVitals

作为钩子参数传递的 metric 对象包含许多属性:

  • id:当前页面加载上下文中指标的唯一标识符
  • name:性能指标的名称。可能的值包括特定于 Web 应用程序的 Web 指标 名称(TTFB、FCP、LCP、FID、CLS)。
  • delta:指标当前值与先前值之间的差异。值通常以毫秒为单位,表示指标值随时间的变化。
  • entries:与指标关联的 性能条目 数组。这些条目提供有关与指标相关的性能事件的详细信息。
  • navigationType:指示触发指标收集的 导航类型。可能的值包括 "navigate""reload""back_forward""prerender"
  • rating:指标值的定性评级,提供性能评估。可能的值是 "good""needs-improvement""poor"。评级通常通过将指标值与指示可接受或次优性能的预定义阈值进行比较来确定。
  • value:性能条目的实际值或持续时间,通常以毫秒为单位。该值提供了指标跟踪的性能方面的定量测量。值的来源取决于正在测量的特定指标,可以来自各种 性能 API

Web 指标

Web 指标 是一组有用的指标,旨在捕获网页的用户体验。包括以下所有 Web 指标:

你可以使用 name 属性处理这些指标的所有结果。

pages/_app.js
import { useReportWebVitals } from 'next/web-vitals'

const handleWebVitals = (metric) => {
switch (metric.name) {
case 'FCP': {
// 处理 FCP 结果
}
case 'LCP': {
// 处理 LCP 结果
}
// ...
}
}

function MyApp({ Component, pageProps }) {
useReportWebVitals(handleWebVitals)

return <Component {...pageProps} />
}
app/components/web-vitals.tsx
'use client'

import { useReportWebVitals } from 'next/web-vitals'

type ReportWebVitalsCallback = Parameters<typeof useReportWebVitals>[0]

const handleWebVitals: ReportWebVitalsCallback = (metric) => {
switch (metric.name) {
case 'FCP': {
// 处理 FCP 结果
}
case 'LCP': {
// 处理 LCP 结果
}
// ...
}
}

export function WebVitals() {
useReportWebVitals(handleWebVitals)
}

自定义指标

除了上面列出的核心指标外,还有一些额外的自定义指标可以测量页面水合和渲染所需的时间:

  • Next.js-hydration:页面开始和完成水合所需的时间长度(以毫秒为单位)
  • Next.js-route-change-to-render:路由更改后页面开始渲染所需的时间长度(以毫秒为单位)
  • Next.js-render:路由更改后页面完成渲染所需的时间长度(以毫秒为单位)

你可以单独处理这些指标的所有结果:

pages/_app.js
import { useReportWebVitals } from 'next/web-vitals'

function handleCustomMetrics(metrics) {
switch (metric.name) {
case 'Next.js-hydration':
// 处理水合结果
break
case 'Next.js-route-change-to-render':
// 处理路由更改到渲染结果
break
case 'Next.js-render':
// 处理渲染结果
break
default:
break
}
}

function MyApp({ Component, pageProps }) {
useReportWebVitals(handleCustomMetrics)

return <Component {...pageProps} />
}

这些指标在支持 用户计时 API 的所有浏览器中都可以工作。

将结果发送到外部系统

你可以将结果发送到任何端点来测量和跟踪站点上的真实用户性能。例如:

function postWebVitals(metrics) {
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 })
}
}

useReportWebVitals(postWebVitals)

提示:如果你使用 Google Analytics,使用 id 值可以让你手动构建指标分布(计算百分位数等)

useReportWebVitals(metric => {
// 如果你像这个示例一样初始化了 Google Analytics,请使用 `window.gtag`:
// 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), // 值必须是整数
event_label: metric.id, // 当前页面加载的唯一 id
non_interaction: true, // 避免影响跳出率。
});
}

了解更多关于 将结果发送到 Google Analytics 的信息。