使用 window.performance 获取性能数据需把握时机、类型和跨域配置:应在 load 事件或早期用 PerformanceObserver 监听,按类型调用 getEntriesByType,跨域资源需服务端设置 Timing-Allow-Origin。

直接用 window.performance 就能拿到高精度、浏览器原生的运行性能数据,关键不是“能不能”,而是“什么时候取、取什么、怎么取准”。
确保时机对:别太早,也别太晚
在 <script></script> 标签里一写就执行 performance.getEntries(),大概率返回空数组——因为浏览器还没来得及记录资源、绘制等条目。
- 推荐放在
window.addEventListener('load', ...)里,此时 HTML 解析完成、图片/CSS/JS 等资源基本加载完毕 - 若需捕获首屏渲染(如 FP、FCP),必须提前注册监听:
performance.getEntriesByType('paint')需配合PerformanceObserver,且要在页面早期(比如 中)初始化 - 兜底可用
setTimeout(() => { ... }, 0)或queueMicrotask,但不建议作为主逻辑
按类型精准获取:别依赖 getEntries() 默认行为
performance.getEntries() 看似“全量”,实际常只返回 navigation 条目。其他类型需显式指定:
-
页面加载过程:用
performance.getEntriesByType('navigation')[0],读取domContentLoadedEventEnd、loadEventEnd、responseStart等字段 -
资源加载详情:用
performance.getEntriesByType('resource'),可分析每个脚本、图片、字体的duration、fetchStart、responseEnd -
渲染关键点:先判断
'paint' in performance,再调performance.getEntriesByType('paint')获取first-paint和first-contentful-paint -
自定义业务耗时:用
performance.mark('api_start')+performance.mark('api_end')+performance.measure('api_duration', 'api_start', 'api_end')
跨域资源要服务端配合:前端无法绕过限制
对 CDN 图片、第三方 JS 等跨域资源,即使出现在 getEntriesByType('resource') 列表里,duration、responseStart 等字段也常为 0。
- 根本原因是浏览器主动脱敏,防止信息泄露
- 解决办法:服务端响应头必须包含
Timing-Allow-Origin: *或具体域名 - 前端加
crossorigin="anonymous"属性只是前提,没服务端头依然无效
用 PerformanceObserver 实时监听异步指标
对于 LCP、FID、CLS 这类动态生成、可能延迟触发的核心指标,轮询 getEntries() 容易漏掉。推荐用观察者模式:
- 创建
new PerformanceObserver,监听['largest-contentful-paint', 'first-input', 'layout-shift'] - 回调中处理每条 entry,例如
entry.startTime就是 LCP 时间点,entry.value是 CLS 累计值 - 注意调用
.observe({ entryTypes: [...] })要在指标可能出现前注册,越早越好
大量免费API接口:立即使用
涵盖生活服务API、金融科技API、企业工商API、等相关的API接口服务。免费API接口可安全、合规地连接上下游,为数据API应用能力赋能!










