useReportWebVitals
使用 useReportWebVitals 钩子测量 Core Web Vitals(LCP、CLS、INP)以及 FCP 和 TTFB,并将其上报到任意分析服务商。
useReportWebVitals 钩子允许你上报 Core Web Vitals,并且可以与你的分析服务结合使用。
传入 useReportWebVitals 的新函数会以截至目前可用的指标进行调用。为防止重复上报数据,请确保回调函数的引用不发生变化(如下方代码示例所示)。
'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>
)
}
由于
useReportWebVitals钩子必须在客户端组件中使用,请为WebVitals组件单独创建一个文件,并在任何导入之前于文件顶部加上'use client'。将该组件导入根布局,以使客户端边界仅限于该模块及其导入。
useReportWebVitals
作为钩子参数传入的 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 Vitals 均已包含:
- Time to First Byte(TTFB)
- First Contentful Paint(FCP)
- Largest Contentful Paint(LCP)
- Cumulative Layout Shift(CLS)
- Interaction to Next Paint(INP)
你可以使用 name 属性来处理这些指标的所有结果。
TypeScript
'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)
}
JavaScript
'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)
}
将结果发送到外部系统
你可以将结果发送到任意端点,以衡量和跟踪 你网站上的真实用户性能。例如:
function postWebVitals(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 })
}
}
useReportWebVitals(postWebVitals)
须知:
如果你使用 Google Analytics,使用
id值可以让你手动构建指标分布(以计算百分位数、 等)
```js
useReportWebVitals((metric) => { // Usewindow.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](https://github.com/GoogleChrome/web-vitals#send-the-results-to-google-analytics)的内容。