JavaScript性能监控主要依靠Performance API,通过performance.getEntriesByType('navigation')、PerformanceObserver监听paint/longtask/layout-shift等事件、performance.mark()/measure()打点测速、performance.memory评估内存(Chrome专属)及主动上报数据实现全面监控。
JavaScript性能监控主要依靠浏览器提供的Performance API,它能精确测量页面加载、脚本执行、渲染、资源加载等各阶段耗时,帮助定位性能瓶颈。
该属性提供导航和资源加载的详细时间戳(如navigationStart、domContentLoadedEventEnd、loadEventEnd),可用于计算白屏时间、首屏时间、DOM就绪时间等核心指标。注意:在现代页面中,performance.timing已被performance.navigation和performance.getEntries()逐步替代,但仍兼容大多数场景。
performance.getEntriesByType('navigation')[0]替代performance.timing获取更准确的导航数据PerformanceObserver监听paint类型事件,捕获first-contentful-paint
可在代码关键路径插入自定义标记(mark),再通过measure计算两点间耗时,适合监控函数执行、模块加载、接口响应等业务逻辑性能。
performance.mark('api-start') → 发起请求前打点performance.mark('api-end') → 接口返回后打点performance.measure('api-duration', 'api-start', 'api-end') → 生成可统计的测量记录performance.getEntriesByName('api-duration')提取结果,便于上报或调试这是现代性能监控的核心方式,支持监听paint、largest-contentful-paint、layout-shift、longtask等关键指标,尤其适合监控用户体验相关数据(如CLS、LCP、INP)。
new PerformanceObserver(cb).observe({entryTypes: ['paint']}),过滤name === 'first-contentful-paint'
entryTypes: ['longtask'],识别JS阻塞问题entryTypes: ['layout-shift'],辅助优化CLS该属性提供JavaScript堆内存使用情况(usedJSHeapSize、totalJSHeapSize),有助于发现内存泄漏或过度对象创建问题。注意:非标准API,仅部分浏览器支持,生产环境需做兼容判断。
performance.memory?.usedJSHeapSize,对比历史趋势performance.getEntriesByType('resource')分析大体积JS/CSS是否未及时释放
闭包或未清理的事件监听器不复杂但容易忽略:所有Performance API采集的数据都需主动上报(如通过sendBeacon)才能用于后续分析,且应控制采样率避免影响用户体验。