前端性能监控怎么做?核心在于利用浏览器提供的接口,用JavaScript主动采集用户真实访问时的各项指标,再汇总分析。下面介绍一套实用的指标采集方案。

为什么需要JavaScript采集指标
很多性能问题只在真实用户设备上出现,实验室测试无法覆盖。通过JavaScript在客户端采集,能获得实际网络、设备、交互延迟等数据,是优化体验的依据。
关键指标与含义
- FCP:首次内容绘制,页面开始显示文本或图像的时间。
- LCP:最大内容绘制,视口中最大元素渲染完成的时间。
- TTFB:首字节时间,请求发起到收到响应的耗时。
- TTI:可交互时间,页面能稳定响应用户输入的时间。
使用Performance API采集
浏览器原生提供window.performance对象,可以拿到导航与资源计时数据。下列代码展示如何取TTFB和FCP。
// 获取导航耗时,计算TTFB
const nav = performance.getEntriesByType('navigation')[0];
const ttfb = nav.responseStart - nav.requestStart;
console.log('TTFB:', ttfb);
// 监听绘制条目,取首次内容绘制
const paintEntries = performance.getEntriesByType('paint');
paintEntries.forEach(function(entry) {
if (entry.name === 'first-contentful-paint') {
console.log('FCP:', entry.startTime);
}
});
基于Web Vitals采集LCP
Google提供的web-vitals库能简化核心指标采集。下面用原生方式观察LCP,不依赖外部库。
// 使用PerformanceObserver观察largest-contentful-paint
try {
const po = new PerformanceObserver(function(list) {
const entries = list.getEntries();
const last = entries[entries.length - 1];
console.log('LCP:', last.startTime);
});
po.observe({ type: 'largest-contentful-paint', buffered: true });
} catch (e) {
console.log('当前浏览器不支持LCP观察');
}
数据上报建议
| 方式 | 说明 |
|---|---|
| sendBeacon | 页面卸载时可靠发送,不阻塞 |
| 图片打点 | 兼容性好,适合简单上报 |
| fetch异步 | 灵活但需注意卸载时机 |
推荐用navigator.sendBeacon上报,代码示意如下。
// 构造性能数据并上报
const data = JSON.stringify({ ttfb: 120, fcp: 300, lcp: 800 });
navigator.sendBeacon('https://monitor.ipipp.com/log', data);
注意事项
采集频率要控制,避免影响业务;敏感字段不要上报;对低端机做降级。
通过上述JavaScript指标采集方法,前端性能监控能低成本落地,持续反映真实用户体验。
前端性能监控JavaScript指标采集Performance_APIWeb_Vitals用户体验修改时间:2026-07-24 19:24:18