useReportWebVitals
测量核心 Web 指标(LCP、CLS、INP)以及 FCP 和 TTFB,并通过 useReportWebVitals hook 将它们报告给任意分析服务提供商。
useReportWebVitals hook 允许你报告核心 Web 指标,并且可以与你的分析服务结合使用。
传递给 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 必须在 Client Component 中使用,请为WebVitals组件创建一个单独的文件,并在任何导入之前于顶部添加'use client'。将该组件导入根布局,使客户端边界仅限于该模块及其导入内容。
useReportWebVitals#
作为 hook 参数传递的 metric 对象由许多属性组成:
id:当前页面加载上下文中该指标的唯一标识符name:性能指标的名称。可能的值包括特定于 Web 应用程序的 Web Vitals 指标名称(TTFB、FCP、LCP、INP、CLS)。delta:该指标的当前值与之前值之间的差值。该值通常以毫秒为单位,表示指标值随时间的变化。entries:与该指标关联的 Performance Entries 数组。这些条目提供与该指标相关的性能事件的详细信息。navigationType:指示触发指标收集的导航类型。值源自 PerformanceNavigationTiming.type,可能包括"navigate"、"reload"、"prerender"、"back-forward"(由"back_forward"规范化而来)、"back-forward-cache"(BFCache 恢复)、"restore"(页面被丢弃后恢复)和"soft-navigation"。navigationId:测量该指标所在导航的 ID。navigationURL:测量该指标所在导航的 URL。这对软导航尤其有用,因为指标可能在 URL 再次改变之后才被报告。navigationStartTime:测量该指标所在导航的开始时间。navigationInteractionId:对于软导航,指触发该导航的交互 ID。rating:指标值的定性评级,提供对性能的评估。可能的值为"good"、"needs-improvement"和"poor"。评级通常通过将指标值与表示可接受或不理想性能的预定义阈值进行比较来确定。value:性能条目的实际值或持续时间,通常以毫秒为单位。该值提供了对指标所跟踪性能方面的定量度量。值的来源取决于所测量的具体指标,可能来自各种 Performance API。
Web Vitals#
Web Vitals 是一组有用的指标,旨在捕捉用户 对网页的体验。以下 Web 指标全部包含在内:
- Time to First Byte (TTFB)
- First Contentful Paint (FCP)
- Largest Contentful Paint (LCP)
- Cumulative Layout Shift (CLS)
- Interaction to Next Paint (INP)
你可以使用 name 属性处理这些指标的所有结果。
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} />
}'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)
}'use client'
import { useReportWebVitals } from 'next/web-vitals'
const handleWebVitals = (metric) => {
switch (metric.name) {
case 'FCP': {
// 处理 FCP 结果
}
case 'LCP': {
// 处理 LCP 结果
}
// ...
}
}
export function WebVitals() {
useReportWebVitals(handleWebVitals)
}自定义指标#
除了上面列出的核心指标之外,还有一些额外的自定义指标用于衡量页面完成 hydrate 和渲染所需的时间:
Next.js-hydration:页面开始和完成 hydrate 所需的时间长度(以毫秒为单位)Next.js-route-change-to-render:路由更改后页面开始渲染所需的时间长度(以毫秒为单位)Next.js-render:路由更改后页面完成渲染所需的时间长度(以毫秒为单位)
Next.js 将这些自定义指标报告给从 pages/_app 导出的 reportWebVitals 函数,并将上面列出的 Web Vitals 报告给 useReportWebVitals。 每个入口点报告各自的指标集,因此请同时导出 reportWebVitals 和该 hook 以接收两者:
import { useReportWebVitals } from 'next/web-vitals'
const logWebVitals = (metric) => {
console.log(metric)
}
export default function MyApp({ Component, pageProps }) {
useReportWebVitals(logWebVitals)
return <Component {...pageProps} />
}
export function reportWebVitals(metric) {
switch (metric.name) {
case 'Next.js-hydration':
// 处理 hydration 结果
break
case 'Next.js-route-change-to-render':
// 处理从路由变更到渲染的结果
break
case 'Next.js-render':
// 处理渲染结果
break
default:
break
}
}这些指标适用于所有支持 User Timing API 的浏览器。
将结果发送到外部系统#
你可以将结果发送到任意端点,以测量和跟踪站点上真实用户的性能。例如:
function postWebVitals(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 })
}
}
useReportWebVitals(postWebVitals)小知识:如果你使用 Google Analytics,可以利用
id值手动构建指标分布(以计算百分位数等)。jsuseReportWebVitals((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的信息。