Performance API通过高精度时间戳提供页面加载、资源请求等性能数据。1. 使用performance.now()获取精确时间;2. 用mark和measure测量自定义逻辑耗时;3. 通过navigation条目计算DNS、TCP、白屏等关键指标;4. 利用PerformanceObserver监听动态资源加载。结合上报机制可构建完整前端监控体系,持续优化用户体验。

前端性能监控是优化用户体验的关键环节,JavaScript中的Performance API为开发者提供了精确测量应用性能的能力。它基于高精度时间戳,能帮助我们获取页面加载、资源请求、脚本执行等关键阶段的耗时信息。
Performance API 核心功能
Performance API 是浏览器内置的接口,位于 window.performance 对象下,主要包含以下几个核心部分:
performance.now():返回自页面加载以来的高精度时间(毫秒),比 Date.now() 更精确,不受系统时钟调整影响。performance.timing:提供页面加载各个阶段的时间戳(已废弃,推荐使用 Navigation Timing Level 2)。performance.getEntries():获取所有已记录的性能条目,包括资源加载、Paint、Frame 等。performance.mark() 和 performance.measure():用于自定义打点和测量时间段。
使用 mark 和 measure 进行自定义性能测量
在复杂应用中,我们常需要测量某段逻辑的执行时间,比如接口响应、组件渲染等。利用 mark 和 measure 可轻松实现:
// 打标记performance.mark('start-data-fetch');fetch('/api/data').then(res => res.json()).then(data => {performance.mark('end-data-fetch');// 记录耗时performance.measure('data-fetch-time', 'start-data-fetch', 'end-data-fetch');});
之后可通过 performance.getEntriesByType(‘measure’) 获取测量结果:
立即学习“Java免费学习笔记(深入)”;
const measures = performance.getEntriesByType('measure');console.log(measures); // [{ name: "data-fetch-time", duration: 120.5, ... }]
监控页面加载性能
利用 navigationStart 和 loadEventEnd 等时间点,可以计算关键性能指标:
const perfData = performance.getEntriesByType("navigation")[0];console.log(`DNS查询耗时: ${perfData.domainLookupEnd - perfData.domainLookupStart}`);console.log(`TCP连接耗时: ${perfData.connectEnd - perfData.connectStart}`);console.log(`白屏时间: ${perfData.responseStart - perfData.navigationStart}`);console.log(`DOM渲染完成: ${perfData.domContentLoadedEventEnd - perfData.navigationStart}`);console.log(`页面完全加载: ${perfData.loadEventEnd - perfData.navigationStart}`);
结合 PerformanceObserver 监听动态资源
对于异步加载的资源(如图片、脚本),可使用 PerformanceObserver 实时监听:
const observer = new PerformanceObserver((list) => { for (const entry of list.getEntries()) { console.log(`${entry.name} 加载耗时: ${entry.duration}`); // 可上报到服务器 }});// 观察资源加载observer.observe({ entryTypes: ['resource'] });
这种方式适用于懒加载图片、动态 import 等场景,能更全面地掌握运行时性能表现。
基本上就这些。Performance API 提供了从页面加载到运行时测量的完整能力,合理使用可以帮助我们定位瓶颈、优化体验,并建立可持续的前端监控体系。不复杂但容易忽略细节,建议结合上报机制长期跟踪。
以上就是JavaScript性能监控_PerformanceAPI的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1539272.html
微信扫一扫
支付宝扫一扫