概述前端性能需覆盖交互与稳定性指标。通过PerformanceObserver采集FID与CLS等关键事件,并以sendBeacon无阻塞上报,结合后端聚合与可视化,形成闭环治理。关键实践与参数采集范围:`largest-contentful-paint`、`first-input`、`layout-shift`INP近似:在交互事件上记录处理耗时作为替代参考上报策略:`navigator.sendBeacon('/metrics', blob)` 在卸载或周期性上报采样比例:按流量配置 `sampleRate` 控制成本示例/配置/实现const metrics = { lcp: null, fid: null, cls: 0, interactions: [] } new PerformanceObserver((entryList) => { for (const e of entryList.getEntries()) metrics.lcp = e.startTime }).observe({ type: 'largest-contentful-paint', buffered: true }) new PerformanceObserver((list) => { for (const e of list.getEntries()) metrics.cls += e.value }).observe({ type: 'layout-shift', buffered: true }) new PerformanceObserver((list) => { const [e] = list.getEntries() metrics.fid = e.processingStart - e.startTime }).observe({ type: 'first-input', buffered: true }) window.addEventListener('click', (ev) => { const t = performance.now() setTimeout(() => { metrics.interactions.push(performance.now() - t) }, 0) }) function flush() { const blob = new Blob([JSON.stringify(metrics)], { type: 'application/json' }) navigator.sendBeacon('/metrics', blob) } window.addEventListener('visibilitychange', () => { if (document.visibilityState === 'hidden') flush() }) setInterval(flush, 10000) 验证指标采集:在真实交互下记录FID与CLS,值合理且随页面变化上报可靠:页面关闭与周期性触发均能成功发送Beacon(网络面板可见)后端聚合:服务端接收并存储数据,仪表盘展示分布与趋势成本控制:采样比例与上报频率在限制内注意事项不同浏览器对性能事件支持差异,需要能力检测INP正式采集建议使用专用库,示例仅近似参考保护隐私与合规,避免携带敏感字段与日志与后端指标联动进行联合分析

发表评论 取消回复