分析 (Analytics)
Next.js 内置支持测量和报告性能指标。您可以使用 useReportWebVitals
钩子自行管理报告,或者使用 Vercel 提供的 托管服务 自动收集和可视化指标。
自定义实现
'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 核心指标 (Web Vitals)
Web 核心指标 是一组用于衡量网页用户体验的关键指标。包含以下所有指标:
您可以通过 name
属性处理所有这些指标的测量结果。
'use client'
import { useReportWebVitals } from 'next/web-vitals'
export function WebVitals() {
useReportWebVitals((metric) => {
switch (metric.name) {
case 'FCP': {
// 处理 FCP 结果
}
case 'LCP': {
// 处理 LCP 结果
}
// ...
}
})
}
'use client'
import { useReportWebVitals } from 'next/web-vitals'
export function WebVitals() {
useReportWebVitals((metric) => {
switch (metric.name) {
case 'FCP': {
// 处理 FCP 结果
}
case 'LCP': {
// 处理 LCP 结果
}
// ...
}
})
}
将结果发送到外部系统
您可以将结果发送到任何端点来测量和跟踪站点的真实用户性能。例如:
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 的信息。