Optimize frontend performance and add route-level web vitals tracking

This commit is contained in:
2569718930@qq.com
2026-03-18 20:38:43 +08:00
parent f0fcb1e379
commit 69f24ddc08
21 changed files with 503 additions and 1386 deletions
@@ -0,0 +1,43 @@
"use client";
import { usePathname } from "next/navigation";
import { useReportWebVitals } from "next/web-vitals";
const TRACKED_METRICS = new Set(["INP", "LCP", "FCP"]);
export function WebVitalsReporter() {
const pathname = usePathname();
useReportWebVitals((metric) => {
if (!TRACKED_METRICS.has(metric.name)) {
return;
}
const payload = {
id: metric.id,
metric: metric.name,
navigationType: metric.navigationType,
pathname: pathname || "/",
rating: metric.rating,
value: metric.value,
};
const body = JSON.stringify(payload);
const url = "/api/vitals";
if (typeof navigator !== "undefined" && typeof navigator.sendBeacon === "function") {
const blob = new Blob([body], { type: "application/json" });
navigator.sendBeacon(url, blob);
return;
}
void fetch(url, {
body,
headers: { "Content-Type": "application/json" },
keepalive: true,
method: "POST",
});
});
return null;
}