性能埋点监控上报
性能监控 API
FP、FCP、LCP 的采集:performance API
如果可以确保页面已经完成了首次绘制和首次内容绘制,可以使用 performance.getEntries 直接获取。
window.performance.getEntriesByType('paint')window.performance.getEntriesByName('first-paint')window.performance.getEntriesByName('first-contentful-paint')
方法2 PerformanceObserver
如果页面还没有开始首次绘制,就需要通过 performanceObserver 监听获取。
new PerformanceObserver((entryList) => { for (const entry of entryList.getEntries()) { console.log('LCP candidate:', entry.startTime, entry); }}).observe({type: 'largest-contentful-paint', buffered: true});
方法3 Navigation Timing API
首次可交互时间: domInteractive - fetchStart
网络请求耗时 (TTFB): responseStart - requestStart
手动监控:LCP
接口提供了监视对 DOM 树所做更改的能力
方法:在首屏内容模块插入一个 div,利用 Mutation Observer API 监听该 div 的 dom 事件,判断该 div 的高度是否大于 0 或者大于指定值,如果大于了,就表示主要内容已经渲染出来,可计算首屏时间。
TBT
TBT(Total Blocking Time) :页面主线程被长任务阻塞的总时间。
long-animation-frame 衡量长动画帧,而不是衡量各个任务。动画帧过长是指渲染更新延迟超过 50 毫秒
lang-task 的缺点
long-task 监控长任务,即占用主线程 50 毫秒或更长时间的任务。该模型充其量只能告诉您发生长任务的容器(顶级文档或
补充
补充:核心 Web Vitals(2024 谷歌体验指标)速记:
- LCP(Largest Contentful Paint):≤ 2.5s 为良好。
- INP(Interaction to Next Paint,已替代 FID):≤ 200ms。
- CLS(Cumulative Layout Shift):≤ 0.1。 上报实战:
PerformanceObserver监听largest-contentful-paint/longtask/layout-shift;错误用window.onerror+unhandledrejection+ React<ErrorBoundary>;网络用PerformanceResourceTiming;上报用navigator.sendBeacon兜底,img.src兜底兜底。
来源整理自:我的有道云笔记



