Skip to main content

useReportWebVitals

useReportWebVitals 钩子允许你报告 核心网络生命力,并且可以与你的分析服务结合使用。

¥The useReportWebVitals hook allows you to report Core Web Vitals, and can be used in combination with your analytics service.

'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 组件。

¥Since the useReportWebVitals hook requires the "use client" directive, the most performant approach is to create a separate component that the root layout imports. This confines the client boundary exclusively to the WebVitals component.

useReportWebVitals

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

¥The metric object passed as the hook's argument consists of a number of properties:

  • id:当前页面加载上下文中指标的唯一标识符

    ¥id: Unique identifier for the metric in the context of the current page load

  • name:性能指标的名称。可能的值包括特定于 Web 应用的 网络生命体 指标名称(TTFB、FCP、LCP、FID、CLS)。

    ¥name: The name of the performance metric. Possible values include names of Web Vitals metrics (TTFB, FCP, LCP, FID, CLS) specific to a web application.

  • delta:指标的当前值与先前值之间的差值。该值通常以毫秒为单位,表示指标值随时间的变化。

    ¥delta: The difference between the current value and the previous value of the metric. The value is typically in milliseconds and represents the change in the metric's value over time.

  • entries:与指标关联的 性能入口 数组。这些条目提供了与指标相关的性能事件的详细信息。

    ¥entries: An array of Performance Entries associated with the metric. These entries provide detailed information about the performance events related to the metric.

  • navigationType:触发收集指标的 导航类型。可能的值包括 "navigate""reload""back_forward""prerender"

    ¥navigationType: Indicates the type of navigation that triggered the metric collection. Possible values include "navigate", "reload", "back_forward", and "prerender".

  • rating:指标值的定性评级,提供性能评估。可能的值为 "good""needs-improvement""poor"。通常通过将指标值与指示可接受或次优性能的预定义阈值进行比较来确定评级。

    ¥rating: A qualitative rating of the metric value, providing an assessment of the performance. Possible values are "good", "needs-improvement", and "poor". The rating is typically determined by comparing the metric value against predefined thresholds that indicate acceptable or suboptimal performance.

  • value:性能条目的实际值或持续时间,通常以毫秒为单位。该值提供了指标所跟踪的性能方面的定量度量。该值的来源取决于所测量的具体指标,并且可以来自各种 性能 API

    ¥value: The actual value or duration of the performance entry, typically in milliseconds. The value provides a quantitative measure of the performance aspect being tracked by the metric. The source of the value depends on the specific metric being measured and can come from various Performance APIs.

网络生命体

¥Web Vitals

网络生命体 是一组有用的指标,旨在捕捉网页的用户体验。以下 Web Vitals 均包含在内:

¥Web Vitals are a set of useful metrics that aim to capture the user experience of a web page. The following web vitals are all included:

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

¥You can handle all the results of these metrics using the name property.

'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
}
// ...
}
})
}
'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 上的用法

¥Usage on Vercel

Vercel 速度见解 没有 useReportWebVitals,而是 @vercel/speed-insights 封装。useReportWebVitals 钩子在本地开发中很有用,或者如果你使用不同的服务来收集 Web Vitals。

¥Vercel Speed Insights does not useReportWebVitals, but @vercel/speed-insights package instead. useReportWebVitals hook is useful in local development, or if you're using a different service for collecting Web Vitals.

将结果发送到外部系统

¥Sending results to external systems

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

¥You can send results to any endpoint to measure and track real user performance on your site. For example:

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 })
}
})

很高兴知道:如果你使用 谷歌分析,则使用 id 值可以让你手动构建度量分布(以计算百分位数等)

¥Good to know: If you use Google Analytics, using the id value can allow you to construct metric distributions manually (to calculate percentiles, etc.)

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/pages/_app.js
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 的更多信息。

¥Read more about sending results to Google Analytics.