Menu

useReportWebVitals

useReportWebVitals hook 允许你报告 核心 Web Vitals,并可以与你的分析服务结合使用。

app/_components/web-vitals.js
"use client";
 
import { useReportWebVitals } from "next/web-vitals";
 
export function WebVitals() {
  useReportWebVitals((metric) => {
    console.log(metric);
  });
}
app/layout.js
import { WebVitals } from "./_components/web-vitals";
 
export default function Layout({ children }) {
  return (
    <html>
      <body>
        <WebVitals />
        {children}
      </body>
    </html>
  );
}

由于 useReportWebVitals hook 需要 "use client" 指令,最优性能的方法是创建一个单独的组件,由根布局导入。这样可以将客户端边界限定在 WebVitals 组件内。

useReportWebVitals

作为 hook 参数传递的 metric 对象包含多个属性:

  • id:当前页面加载上下文中指标的唯一标识符
  • name:性能指标的名称。可能的值包括特定于 Web 应用程序的 Web Vitals 指标名称(TTFB、FCP、LCP、FID、CLS)。
  • delta:当前值与前一个值之间的差异。该值通常以毫秒为单位,表示指标值随时间的变化。
  • entries:与指标关联的 Performance Entries 数组。这些条目提供了与指标相关的性能事件的详细信息。
  • navigationType:指示触发指标收集的 导航类型。可能的值包括 "navigate""reload""back_forward""prerender"
  • rating:指标值的定性评级,提供性能评估。可能的值是 "good""needs-improvement""poor"。评级通常通过将指标值与预定义的阈值进行比较来确定,这些阈值表示可接受的或次优的性能。
  • value:性能条目的实际值或持续时间,通常以毫秒为单位。该值提供了被跟踪性能方面的定量测量。值的来源取决于被测量的特定指标,可以来自各种 Performance API

Web Vitals

Web Vitals 是一组有用的指标,旨在捕捉网页的用户体验。以下所有 Web Vitals 都包括在内:

你可以使用 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 结果
      }
      case "LCP": {
        // 处理 LCP 结果
      }
      // ...
    }
  });
}
app/components/web-vitals.js
"use client";
 
import { useReportWebVitals } from "next/web-vitals";
 
export function WebVitals() {
  useReportWebVitals((metric) => {
    switch (metric.name) {
      case "FCP": {
        // 处理 FCP 结果
      }
      case "LCP": {
        // 处理 LCP 结果
      }
      // ...
    }
  });
}

在 Vercel 上的使用

Vercel Speed Insights 不使用 useReportWebVitals,而是使用 @vercel/speed-insights 包。useReportWebVitals hook 在本地开发或使用不同的服务收集 Web Vitals 时很有用。

将结果发送到外部系统

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

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:
  // 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 的信息。