Performance API 可精确测量前端性能。1. performance.now() 提供微秒级精度,适合测量代码执行耗时;2. PerformanceObserver 异步监听 paint、navigation 等条目,获取 FCP、LCP 等核心指标;3. Navigation Timing API 分析页面加载各阶段耗时,计算 TTFB、DOM Ready、白屏时间等;4. 在 window.onload 后上报 RUM 数据,结合用户环境信息分析真实体验。持续采集与优化关键指标可显著提升性能表现。

要精确测量前端应用的真实性能指标,Performance API 是现代浏览器提供的最可靠工具之一。它能提供高精度的时间戳和关键加载阶段的详细数据,帮助开发者了解页面从开始加载到完全可交互的全过程。
与 Date.now() 不同,performance.now() 提供亚毫秒级精度,并且不受系统时钟调整影响。
const start = performance.now();
doSomething();
const end = performance.now();
console.log(`执行耗时: ${end - start} 毫秒`);
通过 PerformanceObserver 可以异步监听性能条目,避免阻塞主线程。
paint(绘制)、navigation(导航)、resource(资源加载)等类型
const observer = new PerformanceObserver((list) => {
for (const entry of list.getEntries()) {
if (entry.name === 'first-contentful-paint') {
console.log('FCP:', entry.startTime);
}
}
});
observer.observe({ entryTypes: ['paint'] });
performance.timing 和 performance.getEntriesByType('navigation') 提供完整的页面加载时序。
立即学习“前端免费学习笔记(深入)”;
const perfData = performance.getEntriesByType('navigation')[0];
const ttfb = perfData.responseStart - perfData.fetchStart; // 首字节时间
const domReady = perfData.domContentLoadedEventEnd - perfData.fetchStart;
const loadTime = perfData.loadEventEnd - perfData.fetchStart;
console.log({ ttfb, domReady, loadTime });
将 Performance API 数据上报到服务器,用于分析真实用户场景下的性能表现。
window.onload 后采集并发送性能数据
window.addEventListener('load', () => {
setTimeout(() => { // 确保所有性能条目已生成
const navPerf = performance.getEntriesByType('navigation')[0];
const paintEntries = performance.getEntriesByType('paint');
const fcp = paintEntries.find(p => p.name === 'first-contentful-paint')?.startTime;
<pre class="brush:php;toolbar:false;"><pre class="brush:php;toolbar:false;">// 上报数据
navigator.sendBeacon('/log-performance', JSON.stringify({
fcp,
lcp: getLCP(), // 可通过 PerformanceObserver 获取
ttfb: navPerf.responseStart - navPerf.fetchStart,
page: location.pathname
}));}, 100); });
基本上就这些。合理使用 Performance API 能帮你精准定位性能瓶颈,提升用户体验。关键是持续采集、分析并优化真实场景下的指标表现。不复杂但容易忽略细节。
以上就是如何通过Performance API精确测量前端应用的真实性能指标?的详细内容,更多请关注php中文网其它相关文章!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号