目录
分析
Next.js内置了对性能指标的测量和报告支持。
您可以使用useReportWebVitals钩子自行管理报告,或者Vercel提供了一个托管服务,
可以自动收集和可视化指标。
自定义实现
app/_components/web-vitals.js
'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组件中。
查看 API 参考 获取更多信息。
Web Vitals
Web Vitals是一组有用的指标,旨在捕获网页用户体验。以下是所有包含的 Web Vitals:
- Time to First Byte (TTFB)
- First Contentful Paint (FCP)
- Largest Contentful Paint (LCP)
- First Input Delay (FID)
- Cumulative Layout Shift (CLS)
- Interaction to Next Paint (INP)
您可以使用name属性处理所有这些指标的结果。
app/components/web-vitals.tsx
'use client'
import { useReportWebVitals } from 'next/web-vitals'
export function WebVitals() {
useReportWebVitals((metric) => {
switch (metric.name) {
case 'FCP': {
// 处理 FCP 结果
break;
}
case 'LCP': {
// 处理 LCP 结果
break;
}
// ...
}
})
}
将结果发送到外部系统
您可以将结果发送到任何端点,以测量和跟踪您站点上的实际用户性能。例如:
useReportWebVitals((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 })
}
})
备注
如果使用Google Analytics,
使用id值可以允许您手动构建度量分布(以计算百分位数等)。
useReportWebVitals(metric => {
// 如果初始化了 Google Analytics,使用 `window.gtag`,例如:
// 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), // 值必须为整数
event_label: metric.id, // 当前页面加载的唯一 id
non_interaction: true, // 避免影响跳出率
});
});
阅读有关将结果发送到 Google Analytics 的更多信 息。