Menu

性能分析

Next.js 内置了对测量和报告性能指标的支持。你可以使用 useReportWebVitals hook 自行管理报告,或者选择使用 Vercel 提供的 托管服务 来自动收集和可视化指标。

构建你自己的分析系统

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

查看 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 结果
      }
      // ...
    }
  });
}

将结果发送到外部系统

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

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