Skip to main content

分析

Next.js 内置支持测量和报告性能指标。您可以使用useReportWebVitals hook 自行管理报告,或者,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 hook 需要"use client"指令,最有效的方法是创建一个单独的组件,由根布局导入。这将客户端边界仅限制在WebVitals组件内。

参阅API Reference获取更多信息。

Web Vitals

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

您可以使用name属性处理这些指标的所有结果。

"use client";

import { useReportWebVitals } from "next/web-vitals";

export function WebVitals() {
useReportWebVitals((metric) => {
switch (metric.name) {
case "FCP": {
// handle FCP results
}
case "LCP": {
// handle LCP results
}
// ...
}
});
}
"use client";

import { useReportWebVitals } from "next/web-vitals";

export function WebVitals() {
useReportWebVitals((metric) => {
switch (metric.name) {
case "FCP": {
// handle FCP results
}
case "LCP": {
// handle LCP results
}
// ...
}
});
}

将结果发送到外部系统

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

useReportWebVitals((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 });
}
});

您需要知道: 如果您使用Google Analytics, 使用id值可以让您手动构建指标分布(以计算百分位数等)

useReportWebVitals((metric) => {
// Use `window.gtag` if you initialized Google Analytics as this example:
// 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
), // values must be integers
event_label: metric.id, // id unique to current page load
non_interaction: true, // avoids affecting bounce rate.
});
});

了解更多关于 将结果发送到 Google Analytics的信息。