Performance API 提供高精度性能监控,通过 performance.now()、mark/measure、navigation 和 resource 等接口,精确测量页面加载、资源请求及自定义时段性能,助力优化用户体验。

网页性能直接影响用户体验,而准确掌握页面加载与运行时的表现,是优化的关键。Performance API 是现代浏览器提供的一套原生接口,能够帮助开发者精确测量页面性能。它不依赖第三方工具,直接从浏览器获取高精度时间戳和关键性能指标。
了解 Performance API 核心对象
Performance 接口是 Performance API 的核心,可通过全局的 window.performance 访问。它提供多种方法和属性,用于记录时间点和获取性能数据。
主要组成部分包括:
- performance.now():返回自页面开始加载以来的高精度时间(毫秒),比 Date.now() 更精确,不受系统时钟调整影响。
- performance.timing:提供页面加载各阶段的时间戳(已废弃,推荐使用 Navigation Timing Level 2)。
- performance.getEntries():获取所有已记录的性能条目,如资源加载、重定向等。
- performance.mark() 和 performance.measure():用于自定义标记和测量时间段。
使用 mark 和 measure 记录自定义性能
在复杂应用中,你可能需要测量某段 JavaScript 执行时间或异步操作耗时。Performance API 提供了用户计时(User Timing)接口来实现这一点。
操作步骤如下:
- 用 performance.mark('start') 在关键位置打标记。
- 执行目标代码后,调用 performance.mark('end')。
- 使用 performance.measure('label', 'start', 'end') 计算两者之间的时间差。
- 通过 performance.getEntriesByType('measure') 查看结果。
示例:
performance.mark('fetch-start');fetch('/api/data').then(() => {
performance.mark('fetch-end');
performance.measure('fetchDuration', 'fetch-start', 'fetch-end');
});
const measures = performance.getEntriesByType('measure');
console.log(measures[0].duration); // 输出请求耗时
获取页面加载性能指标
Navigation Timing API 是 Performance API 的一部分,可获取页面导航和加载的详细时间。虽然 timing 属性已被弃用,但可用 performance.getEntriesByType('navigation') 替代。
常见关键指标包括:
- loadEventEnd - fetchStart:页面总加载时间。
- responseStart - requestStart:后端响应时间。
- domContentLoadedEventStart - fetchStart:DOM 准备就绪耗时。
获取方式:
const navEntries = performance.getEntriesByType('navigation');const nav = navEntries[0];
console.log('DNS 查询耗时:', nav.domainLookupEnd - nav.domainLookupStart);
console.log('TCP 建连耗时:', nav.connectEnd - nav.connectStart);
console.log('白屏时间:', nav.responseStart - nav.fetchStart);
console.log('首包时间:', nav.responseStart);
监控资源加载性能
Resource Timing API 可统计页面中每个资源(如 JS、CSS、图片)的加载表现。调用 performance.getEntriesByType('resource') 即可获取。
可用于分析:
- 哪些资源加载最慢。
- 是否存在长时间阻塞的脚本。
- CORS 资源是否配置了 Timing-Allow-Origin,否则数据会受限。
示例:找出加载时间超过 100ms 的资源
const resources = performance.getEntriesByType('resource');resources.forEach(res => {
if (res.duration > 100) {
console.log(`${res.name} 加载耗时: ${res.duration}ms`);
}
});
基本上就这些。Performance API 提供了轻量、标准、高效的方式监控前端性能。合理使用 mark、measure 和各类 timing 数据,能帮你快速定位瓶颈,提升用户体验。不复杂但容易忽略细节,比如清除标记(clearMarks/clearMeasures)避免内存堆积。实际项目中可结合上报机制,将关键指标发送到服务端分析。











