直接调用Performance API获取瞬时性能快照,需分四类:导航快照(document.readyState==='complete'后取navigation条目)、资源快照(window.load后过滤img/css/script)、渲染快照(<head>内同步监听paint和largest-contentful-paint)、运行时快照(performance.mark/measure打点)。

直接在关键节点调用 Performance API 获取瞬时性能数据,就能拿到一份可靠的页面性能快照。核心是选对时机、选对类型、选对字段,而不是等所有数据“自然汇总”。
导航快照:只抓首次加载的完整链路
页面性能快照的第一块拼图,是导航过程的端到端耗时。它反映用户从输入 URL 到页面可交互的整体体验。
- 必须等 document.readyState === 'complete' 或监听 window.load 后再执行,提前调用会返回空数组
- 调用 performance.getEntriesByType('navigation')[0],它包含 domainLookupStart、connectEnd、responseStart、domContentLoadedEventEnd、loadEventEnd 等 20+ 字段
- 所有时间值都基于 performance.timeOrigin,直接相减即可得各阶段耗时,例如:
DNS 查询耗时 = nav.domainLookupEnd - nav.domainLookupStart - 注意:SPA 路由跳转不会生成新 navigation 条目,这个快照仅代表页面初始加载
资源快照:锁定首屏关键资源加载表现
光看整体加载不够,还得知道哪些资源拖慢了首屏——特别是图片、CSS 和核心 JS。
- 在 window.load 后调用 performance.getEntriesByType('resource'),确保初始资源已全部加载完成
- 过滤出首屏相关资源:entry.initiatorType === 'img' || entry.initiatorType === 'css' || entry.initiatorType === 'script'
- 检查 entry.duration > 0,避免跨域资源未加 crossorigin 属性导致 duration 为 0
- 重点关注 transferSize(实际传输体积)和 duration(总耗时),识别大体积或高延迟资源
渲染快照:捕获不可逆的首屏绘制时刻
FP、FCP、LCP 这类指标一旦发生就无法重放,错过就永久丢失,必须前置监听。
- PerformanceObserver 必须写在 <head> 内的同步 script 中,不能加 defer、不能包在函数里、不能等任何初始化回调
- 监听 paint 类型获取 FCP:
if (entry.name === 'first-contentful-paint') { console.log('FCP:', entry.startTime) } - 监听 largest-contentful-paint 类型获取 LCP:
const lcpEntry = list.getEntries().pop(),取最后一个才是稳定终值 - 不要混用 paint 和 largest-contentful-paint 在同一个 observer,它们属于不同 entryTypes
运行时快照:标记业务关键路径耗时
除了浏览器自动记录的指标,你还可以主动打点,把性能数据和业务逻辑对齐。
- 在关键操作开始前调用 performance.mark('page-start'),结束后调用 performance.mark('page-render-end')
- 用 performance.measure('render-time', 'page-start', 'page-render-end') 计算区间耗时
- 通过 performance.getEntriesByName('render-time')[0].duration 提取结果
- 这类自定义快照适合衡量首屏渲染、列表加载、表单提交等具体业务环节


















