☰
性能检测埋点方案选择
2026/10/12 7:27:17 网站建设 项目流程

✅一、交给 web‑vitals(不要自己手写 PerformanceObserver)

库内部已经封装好PerformanceObserver,处理了 buffered、SPA 软导航、BFCache、多次候选值、浏览器兼容性,RUM 采集直接用GitHub

  • LCP 最大内容绘制
  • INP 交互到下一次绘制(新版核心指标,替代 FID)
  • CLS 累积布局偏移
  • FCP 首次内容绘制
  • TTFB 首字节时间
import {onLCP,onINP,onCLS,onFCP,onTTFB} from 'web‑vitals' onLCP(上报函数) onINP(上报函数) onCLS(上报函数) onFCP(上报函数) onTTFB(上报函数)

底层依然是 Performance API,只是复杂规则由谷歌维护,业务埋点不要重复造轮子。

✅二、必须自己手写原生 Performance API(web‑vitals 不提供)

1)导航耗时 navigation

DNS、TCP、TLS、DOMContentLoaded、load 完整时间线performance.getEntriesByType('navigation')

window.addEventListener('load', () => { 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('DOMContentLoaded', nav.domContentLoadedEventEnd); console.log('load完成', nav.loadEventEnd); })

2)资源加载 timing(js/css/img/font)

各个静态资源下载、解析耗时PerformanceObserver type="resource"

const resObserver = new PerformanceObserver((list) => { list.getEntries().forEach(entry => { console.log('资源地址', entry.name); console.log('下载耗时', entry.responseEnd - entry.startTime); }) }) resObserver.observe({type:'resource',buffered:true})

3)长任务 LongTask / LoAF 长动画帧(主线程阻塞)

定位卡顿根源,分析 TBT 总阻塞时长PerformanceObserver type="longtask"

const longTaskObserver = new PerformanceObserver((list) => { list.getEntries().forEach(entry => { console.log('长任务阻塞时长(ms)', entry.duration); }) }) longTaskObserver.observe({type:'longtask',buffered:true})

4)自定义打点(SPA 路由、接口、组件挂载、自定义首屏)

performance.mark()/performance.measure()

比如 Vue/React 路由切换耗时、接口耗时、自定义首屏完成时间,web‑vitals 管不了业务自定义节点。

//开始打点 performance.mark('route-start') setTimeout(()=>{ //结束打点,计算间隔 performance.mark('route-end') performance.measure('route-cost','route-start','route-end') const measureList = performance.getEntriesByName('route-cost') console.log('路由耗时ms',measureList[0].duration) //清理,避免内存堆积 performance.clearMarks(); performance.clearMeasures(); },800)

5)TTI、TBT

浏览器没有直接原生条目,web‑vitals 也不输出; 需要收集长任务、网络空闲窗口自己算法算出,实验室指标,线上 RUM 很少采集。

6)ElementTiming 自定义元素计时

指定某个 DOM(广告、模块)渲染耗时

html 增加elementtiming属性

<div elementtiming="ad-block">广告模块</div>

JS 采集

const eleObserver = new PerformanceObserver(list=>{ list.getEntries().forEach(e=>{ console.log('指定DOM渲染完成时间',e.renderTime) }) }) eleObserver.observe({type:'element',buffered:true})

✅三、一句话选型口诀

  1. 用户体验核心 5 大指标(LCP/INP/CLS/FCP/TTFB)→ web‑vitals
  2. 资源、长任务、导航细节、业务自定义打点、SPA 路由耗时 → 原生 PerformanceObserver /mark+measure
  3. TTI/TBT 属于实验室指标,线上一般不采集

✅四、面试补充坑点

  1. web‑vitals 只能拿到标准体验指标,不能定位阻塞的 JS 文件、图片资源,排查问题依然要原生资源 / 长任务监控;
  2. web‑vitals 不支持自定义 DOM 计时,业务首屏、路由切换埋点必须自己 mark;
  3. 不要自己手写 LCP/CLS/INP 采集,实现规则复杂容易不准,线上 RUM 优先库。

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询