JavaScript性能监控核心是Performance API,优先用PerformanceObserver捕获FCP、LCP、CLS等Web Vitals指标,辅以performance.mark/measure自定义打点,通过sendBeacon上报并采样。
JavaScript 实现性能监控,核心是利用 Performance API(尤其是 performance.timing 和 performance.getEntriesByType),配合关键用户感知指标(如 FCP、LCP、CLS)来真实反映页面加载与交互体验。重点不是堆砌数据,而是捕获对用户体验有实际影响的时间节点。
适用于较老浏览器或需兼容 legacy 场景(注意:Navigation Timing Level 1 已被 Level 2 取代,但仍有参考价值):
performance.timing.navigationStart:导航开始(上一页面卸载或当前页面首次触发导航)performance.timing.domContentLoadedEventEnd:DOM 解析完成且 DOMContentLoaded 事件执行完毕performance.timing.loadEventEnd:window.load 事件完成计算示例:
const timing = performance.timing;
const domReady = timing.domContentLoadedEventEnd - timing.navigationStart;
const pageLoad = timing.loadEventEnd - timing.navigationStart;
console.log(`DOM就绪耗时: ${domReady}ms, 页面完全加载: ${pageLoad}ms`);⚠️ 注意:该接口在现代项目中建议仅作兜底,优先使用更精准的 PerformanceObserver。
这是当前推荐方式,能捕获用户真实感知的关键性能指标:
”代码示例(监听 LCP 和 CLS):
new PerformanceObserver((entryList) => {
for (const entry of entryList.getEntries()) {
if (entry.name === 'largest-contentful-paint') {
console.log('LCP 时间:', Math.round(entry.startTime));
}
}
}).observe({ entryTypes: ['largest-contentful-paint'] });
new PerformanceObserver((entryList) => {
for (const entry of entryList.getEntries()) {
if (entry.value > 0.1) { // 布局偏移大于 0.1 视为不良体验
console.log('CLS 偏移:', entry.value);
}
}
}).observe({ entryTypes: ['layout-shift'] });
针对业务关键路径(如首屏渲染完成、某个组件挂载、API 数据返回后视图更新),可主动标记时间点:
performance.mark('xxx-start') 打起点performance.mark('xxx-end') 打终点performance.measure('xxx-duration', 'xxx-start', 'xxx-end') 计算差值performance.getEntriesByName('xxx-duration') 获取结果例如监控 React 组件首次渲染耗时:
performance.mark('hero-component-mount-start');
// ... 组件挂载逻辑
performance.mark('hero-component-mount-end');
performance.measure('hero-render-time', 'hero-component-mount-start', 'hero-component-mount-end');
const measure = performance.getEntriesByName('hero-render-time')[0];
console.log(Hero组件首渲耗时: ${measure.duration.toFixed(1)}ms);
监控数据需合理上报,避免影响用户体验:
navigator.sendBeacon() 发送,确保页面卸载前也能发出请求简单上报示例:
function reportToBackend(metric) {
const data = JSON.stringify(metric);
navigator.sendBeacon('/api/perf', data);
}