Performance API是浏览器内置的高精度性能分析工具,支持导航、资源加载、自定义打点、长任务监控及内存查看,数据通过performance.getEntriesByType等方法获取,推荐用sendBeacon上报。

Performance API 是浏览器内置的性能分析工具,能精确测量页面加载、资源加载、脚本执行等关键时间点。它不依赖第三方库,开箱即用,数据来自底层计时器(如 performance.now()),精度达微秒级。
获取基础性能指标
通过 performance.timing(已废弃但部分旧环境仍可读)或更推荐的 performance.getEntriesByType() 和 performance.navigation(已弃用)替代方案 —— 优先使用 performance.getEntries() 或 performance.getEntriesByType('navigation') 获取导航性能数据:
-
performance.getEntriesByType('navigation')[0]返回当前页面导航记录,含loadEventStart、domContentLoadedEventEnd、responseEnd等字段 -
performance.getEntriesByType('resource')获取所有资源(JS/CSS/图片等)的加载耗时,每项含name、duration、startTime、fetchStart等 -
performance.memory(仅 Chromium)可查看 JS 堆内存使用情况(需开启--enable-precise-memory-info标志)
打点测量自定义代码段耗时
用 performance.mark() 和 performance.measure() 在关键逻辑前后插入标记,再计算差值:
在 Java 中初始化和管理阿里云 SDK客户端。包括单例模式、线程安全、endpoint 与 region 配置、VPC 终端节点、同步与异步等。
- 在函数开始前调用
performance.mark('render-start') - 结束后调用
performance.mark('render-end') - 再执行
performance.measure('render-time', 'render-start', 'render-end') - 用
performance.getEntriesByName('render-time')获取结果,duration字段即为耗时(毫秒,精度高于Date.now())
监控长任务与主线程阻塞
长任务(Long Task)指执行时间 ≥ 50ms 的同步脚本,易导致页面卡顿。可通过 PerformanceObserver 实时监听:
立即学习“Java免费学习笔记(深入)”;
- 创建观察器:
const obs = new PerformanceObserver(list => { list.getEntries().forEach(entry => console.log('长任务:', entry.duration)); }); - 启用监听:
obs.observe({entryTypes: ['longtask']}); - 注意:需在页面早期注册(如
<script>放在<head>),否则可能错过首屏前的长任务
导出与上报性能数据
采集到的数据需及时序列化并上报,避免因页面卸载丢失:
- 用
performance.toJSON()可快速获取当前 performance 对象快照(不含动态条目) - 推荐组合使用:
performance.getEntriesByType('navigation')[0]+performance.getEntriesByType('resource')+ 自定义mark/measure结果 - 上报建议用
navigator.sendBeacon(),确保页面关闭前也能发出请求(比fetch更可靠)


















