核心价值客户端实时采集核心性能指标并上报,结合服务端聚合实现持续优化。与页面结构与资源策略协同,降低波动并提升关键体验。客户端采集// app/vitals.tsx 'use client' import { useEffect } from 'react' export default function Vitals() { useEffect(() => { const send = (name: string, value: number) => { navigator.sendBeacon('/api/vitals', JSON.stringify({ name, value, ts: Date.now() })) } try { const po = new PerformanceObserver((list) => { for (const entry of list.getEntries()) { if (entry.entryType === 'largest-contentful-paint') send('LCP', (entry as any).renderTime || entry.startTime) if (entry.entryType === 'event') send('INP', (entry as any).interactionId ? entry.duration : entry.duration) if (entry.entryType === 'layout-shift') { const ls = entry as any if (!ls.hadRecentInput) send('CLS', ls.value) } } }) po.observe({ type: 'largest-contentful-paint', buffered: true }) po.observe({ type: 'event', buffered: true, durationThreshold: 16 }) po.observe({ type: 'layout-shift', buffered: true }) } catch {} }, []) return null } // app/layout.tsx import Vitals from './vitals' export default function RootLayout({ children }: { children: React.ReactNode }) { return ( <html> <body> {children} <Vitals /> </body> </html> ) } 服务端接收// app/api/vitals/route.ts export const runtime = 'edge' export async function POST(req: Request) { const json = await req.json() // 在真实环境中写入日志或传至观测后端 return Response.json({ ok: true }, { headers: { 'Cache-Control': 'no-store' } }) } 治理建议对 LCP 元素使用占位与预加载;对 INP 优化交互与渲染竞争;对 CLS 保持尺寸占位与稳定排版。结合 `Server-Timing` 与 RUM 汇总,形成线上与本地一致的观测体系。结论Web Vitals 采集与服务端接收在 Next.js 15 中实现简洁,协同治理可显著提升核心体验指标并持续优化。

点赞(0) 打赏

评论列表 共有 0 条评论

暂无评论
立即
投稿

微信公众账号

微信扫一扫加关注

发表
评论
返回
顶部
2.067184s