Performance API 可精确采集页面加载、渲染及核心网页指标,通过 PerformanceObserver 监听 LCP、FID、CLS 等数据,结合 getEntriesByType 分析资源加载性能,并在 load 后上报至服务端,实现持续监控与瓶颈定位。
前端性能直接影响用户体验,而浏览器提供的 Performance API 是进行深度性能分析的核心工具。它能提供页面加载、资源请求、脚本执行等关键时间点的精确数据,帮助开发者定位瓶颈。
理解 Performance API 的核心接口
Performance API 包含多个子接口,用于采集不同类型的数据:
- performance.timing:已废弃,建议使用 Navigation Timing Level 2
- performance.navigation:获取导航类型(如刷新、前进/后退)和重定向次数
- PerformanceObserver:监听新性能条目(如 LCP、FID、CLS)的推荐方式
- performance.getEntries():获取所有已记录的性能条目,包括资源加载、Paint、Navigation 等
注意:现代应用应优先使用 PerformanceObserver
配合 entryTypes
监听关键指标,避免遗漏异步生成的性能数据。
采集关键性能指标(Core Web Vitals)
Google 推出的核心网页指标是衡量用户体验的关键,Performance API 支持通过 PerformanceObserver
捕获:
- LCP(最大内容绘制):监听
largest-contentful-paint
类型条目,判断主内容渲染时间 - FID(首次输入延迟):监听
first-input
,测量用户首次交互的响应延迟 - CLS(累积布局偏移):监听
layout-shift
,检测页面意外布局变化
示例代码:
立即学习“前端免费学习笔记(深入)”;
<font face="monospace"> const observer = new PerformanceObserver((list) => { for (const entry of list.getEntries()) { console.log(entry.name, entry.startTime, entry.value); } }); observer.observe({ entryTypes: ['largest-contentful-paint', 'first-input', 'layout-shift'] }); </font>
分析资源加载与渲染性能
通过 performance.getEntriesByType('navigation')
可获取页面加载全过程的时间节点:
- domContentLoadedEventEnd:DOM 解析完成并执行完同步脚本
- loadEventEnd:页面所有资源(如图片、iframe)加载完成
- secureConnectionStart:HTTPS 握手开始时间,可用于计算 TLS 耗时
资源级别分析可通过 getEntriesByType('resource')
获取每个脚本、样式、图片的加载耗时、DNS 查询、TCP 连接等细节,识别慢资源。
上报与持续监控
采集到的数据需上报至服务端进行聚合分析。建议在 window.onload
后发送,避免影响关键渲染路径:
<font face="monospace"> window.addEventListener('load', () => { setTimeout(() => { const navigation = performance.getEntriesByType('navigation')[0]; const resources = performance.getEntriesByType('resource'); // 发送数据到分析后台 navigator.sendBeacon('/log', JSON.stringify({ navigation, resources })); }, 1000); }); </font>
结合日志系统可建立性能基线,设置告警阈值,及时发现回归问题。
基本上就这些。合理使用 Performance API 能深入掌握前端性能表现,关键是持续采集、对比趋势、定位瓶颈。
以上就是如何利用Performance API进行js 前端 json go 浏览器 工具 ai win dns google Resource 接口 dom 异步 input https iframe