浏览器原生performance api可准确测量首屏指标:用performanceobserver监听'paint'获取fp/fcp、监听'largest-contentful-paint'捕获lcp;辅以performance.mark/measurement做业务级打点,chrome devtools可直接查看各指标数值。

直接用浏览器原生的 Performance API 就能准确测出首屏关键指标,不需要第三方库。核心是结合 PerformanceObserver 监听绘制事件,再辅以 performance.getEntriesByType 和 performance.mark 做补充验证。
用 PerformanceObserver 捕获 FP/FCP/LCP
这是最推荐的方式,实时、精准、符合规范:
- 监听
'paint'类型,可拿到first-paint和first-contentful-paint的时间戳 - 监听
'largest-contentful-paint'类型,能捕获 LCP 元素、渲染时间及具体节点信息 - 所有事件在页面加载过程中动态触发,支持多次候选元素更新后的最终值
示例代码:
new PerformanceObserver((entryList) => {
for (const entry of entryList.getEntries()) {
if (entry.name === 'first-paint') console.log('FP:', entry.startTime);
if (entry.name === 'first-contentful-paint') console.log('FCP:', entry.startTime);
}
}).observe({ entryTypes: ['paint'] });
new PerformanceObserver((entryList) => {
const lastEntry = entryList.getEntries().pop();
if (lastEntry) {
console.log('LCP:', lastEntry.startTime, 'element:', lastEntry.element);
}
}).observe({ entryTypes: ['largest-contentful-paint'] });
手动计算 TTI(需组合判断)
TTI 没有单一事件,但可通过以下逻辑推断:
- 监听
'longtask',确认主线程是否持续空闲(5秒内无 ≥50ms 任务) - 结合
navigationStart和资源加载完成时间(loadEventEnd或domContentLoadedEventEnd) - 实际 TTI ≈ 首次满足「5秒空闲窗口」的起始时间点
注意:生产环境建议用 web-vitals 库,它已封装好鲁棒的 TTI 估算逻辑。
开发调试时快速验证(不写代码)
无需改业务代码,也能即时看指标:
- Chrome DevTools → Performance 面板 → 录制刷新过程 → 查看 Timings 区域的 FP/FCP/LCP/TTI 标记
- Lighthouse 面板 → 运行审计 → 查看 Performance 报告中的各项得分和原始数值
- Network 面板勾选 “Disable cache” + 切换 “Slow 3G”,模拟弱网下首屏表现
补充打点:对关键路径做业务级测量
FP/FCP/LCP 是浏览器定义的“渲染完成”,但用户感知的“首屏可用”可能更晚,比如数据请求+模板渲染后:
- 在数据请求开始前
performance.mark('api-start') - 在列表首次渲染完成后
performance.mark('list-first-render') - 用
performance.measure('first-screen-ready', 'api-start', 'list-first-render')记录业务首屏耗时 - 该结果可与 FCP/LCP 对比,定位是渲染慢还是逻辑慢
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南











