Performance API是浏览器内置的性能监控工具,通过window.performance提供高精度时间戳和页面加载、资源请求等数据。它包含Navigation Timing、Resource Timing、User Timing和Paint Timing等接口,可测量页面加载耗时、DOM渲染时间、关键渲染指标如FP和FCP,并支持自定义标记监控函数执行时间。结合PerformanceObserver和navigator.sendBeacon,能实现细粒度性能采集与上报,帮助分析白屏时间、资源阻塞等问题,支持多维度性能优化与告警。

前端性能监控是提升用户体验的关键环节,而浏览器提供的 Performance API 是实现这一目标的核心工具。它能帮助开发者精准测量页面加载、资源请求、脚本执行等关键阶段的耗时,从而定位性能瓶颈并进行针对性优化。
Performance API 是现代浏览器内置的一套接口,用于获取高精度的时间戳和页面性能相关数据。其核心对象是 window.performance,提供了一系列方法和属性,比如 performance.now() 可以获取毫秒级精确时间,比 Date.now() 更适合做性能测量。
更重要的是,Performance API 提供了多个子接口:
通过以下代码可以快速获取页面加载的核心性能数据:
立即学习“前端免费学习笔记(深入)”;
function getPerformanceMetrics() {
const perfData = performance.timing;
const loadTime = perfData.loadEventEnd - perfData.navigationStart;
const domReadyTime = perfData.domContentLoadedEventEnd - perfData.navigationStart;
<p>console.log(<code>页面完全加载耗时: ${loadTime}ms</code>);
console.log(<code>DOM ready 耗时: ${domReadyTime}ms</code>);</p><p>// 使用 PerformanceObserver 获取更详细的条目
const observer = new PerformanceObserver((list) => {
list.getEntries().forEach((entry) => {
if (entry.entryType === 'paint') {
console.log(<code>${entry.name}: ${entry.startTime}ms</code>);
}
});
});</p><p>observer.observe({ entryTypes: ['paint'] });
}</p><p>getPerformanceMetrics();</p>这段代码输出的内容包括:
除了系统自动采集的数据,你还可以手动标记代码中重要操作的执行时间:
// 标记函数开始
performance.mark('start-heavy-task');
<p>heavyComputation(); // 某个耗时操作</p><p>// 标记函数结束
performance.mark('end-heavy-task');</p><p>// 测量耗时
performance.measure('heavy-task-duration', 'start-heavy-task', 'end-heavy-task');</p><p>// 输出结果
const measures = performance.getEntriesByType('measure');
console.log(measures); // 打印耗时统计</p>这种方式非常适合监控复杂计算、组件渲染、API 请求处理等业务逻辑的性能表现。
采集到性能数据后,应定期上报到服务器进行聚合分析。例如在页面卸载前发送关键指标:
window.addEventListener('beforeunload', () => {
const fcpEntry = performance.getEntriesByName('first-contentful-paint')[0];
if (fcpEntry) {
navigator.sendBeacon('/log-performance', JSON.stringify({
fcp: fcpEntry.startTime,
url: window.location.href,
timestamp: Date.now()
}));
}
});
navigator.sendBeacon 确保数据在页面关闭时仍能可靠发送,不会被中断。
结合后端系统,你可以实现:
基本上就这些。合理使用 Performance API,不仅能掌握页面真实性能状况,还能为后续优化提供数据支撑。不复杂但容易忽略。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号