通过Performance API可精准测量前端性能。1. 利用window.performance获取页面加载各阶段时间戳,推荐使用getEntriesByType('navigation')获取TTFB、DOMContentLoaded及完全加载时间;2. 使用User Timing API的mark和measure方法标记并测量自定义代码段执行耗时,适用于监控关键函数或组件渲染;3. 调用getEntriesByType('resource')分析静态资源加载性能,识别慢资源与阻塞问题,并检查压缩情况;4. 结合Long Tasks API与PerformanceObserver监听主线程中超过50ms的长任务,发现卡顿根源;5. 在beforeunload事件中通过sendBeacon上报性能数据,实现持续监控。这些方法从真实用户视角定位性能瓶颈,提升用户体验。

前端性能直接影响用户体验,JavaScript 的 Performance API 提供了精确测量页面加载、脚本执行和资源加载时间的能力。通过它,你可以定位性能瓶颈,优化关键路径。
浏览器的 window.performance 对象记录了从导航开始到页面加载完成的各个阶段的时间戳。这些数据来自 Navigation Timing API 和 User Timing API。
获取页面加载关键指标:
立即学习“Java免费学习笔记(深入)”;
performance.getEntriesByType('navigation')[0].responseStart - performance.timing.navigationStart
performance.timing.domContentLoadedEventEnd - performance.timing.navigationStart
performance.timing.loadEventEnd - performance.timing.navigationStart
现代推荐使用 performance.getEntriesByType('navigation') 替代已废弃的 performance.timing。
你可以手动标记 JavaScript 中的关键函数或模块,测量其执行耗时。
示例:测量某个函数的执行时间
// 开始标记
performance.mark('start-heavy-task');
<p>heavyFunction(); // 要测量的函数</p><p>// 结束标记
performance.mark('end-heavy-task');</p><p>// 创建测量
performance.measure('heavy-function-duration', 'start-heavy-task', 'end-heavy-task');</p><p>// 获取结果
const measures = performance.getEntriesByName('heavy-function-duration');
console.log(measures[0].duration); // 输出执行毫秒数
适合用于监控组件渲染、数据处理、API 解析等耗时操作。
通过 performance.getEntriesByType('resource') 可获取所有静态资源(JS、CSS、图片、字体等)的加载详情。
分析资源瓶颈:
fetchStart 到 responseEnd 时间,识别加载慢的资源。transferSize 和 encodedBodySize 判断是否开启压缩。示例:找出加载最慢的资源
const resources = performance.getEntriesByType('resource');
const slowest = resources.sort((a, b) => (b.responseEnd - b.startTime) - (a.responseEnd - a.startTime))[0];
console.log('最慢资源:', slowest.name, '耗时:', slowest.responseEnd - slowest.startTime, 'ms');
长时间运行的任务会阻塞 UI 渲染,造成卡顿。使用 Long Tasks API 可捕获执行超过 50ms 的任务。
配合 PerformanceObserver 使用:
const observer = new PerformanceObserver((list) => {
for (const entry of list.getEntries()) {
console.warn('长任务检测:', entry);
// 上报到监控系统
}
});
observer.observe({entryTypes: ['longtask']});
有助于发现未分片的大计算、同步 DOM 操作等问题。
将采集的性能数据发送到服务端进行聚合分析。
示例:页面卸载前上报关键指标
window.addEventListener('beforeunload', () => {
const nav = performance.getEntriesByType('navigation')[0];
navigator.sendBeacon('/log', JSON.stringify({
ttfb: nav.responseStart,
domReady: nav.domContentLoadedEventEnd,
loadTime: nav.loadEventEnd,
// 其他自定义 measure
}));
});
navigator.sendBeacon 确保数据在页面关闭时仍能可靠发送。
基本上就这些方法。合理使用 Performance API 能帮你从用户真实体验角度定位问题,而不是仅依赖本地测试。
以上就是如何通过 JavaScript 的 Performance API 进行前端性能监控与瓶颈分析?的详细内容,更多请关注php中文网其它相关文章!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号