如何确定页面的可用性时间,什么是 Performance API?
参考答案
什么是"页面可用性时间"
指页面达到用户可正常使用的时间点,通常对应:
- TTI(Time to Interactive):主线程空闲、能稳定响应输入的时间。
- 首次可交互:用户能点击/输入并得到响应的时刻。
- 业务口径:"首屏内容可见 + 关键交互可用"。
Performance API 是什么
浏览器提供的性能度量接口集合,用于采集各阶段耗时:
- **
performance.now()**:高精度相对时间戳(微秒级),用于打点。 - **
performance.timing(已废弃)/performance.getEntriesByType('navigation')[0]**:包含domainLookupStart/End、connectStart、responseStart(TTFB)、domContentLoadedEventEnd、loadEventEnd等。 - **
performance.getEntriesByType('resource')**:每个资源的耗时、体积、是否命中缓存。 - **
PerformanceObserver**:订阅paint(FCP)、largest-contentful-paint(LCP)、layout-shift(CLS)、first-input(FID)、longtask、navigation、resource等条目。 - **
performance.mark()/measure()**:自定义标记与区间测量。 - **
performance.memory**(Chrome):堆内存信息。
如何确定可用性时间
// 简化示例:用长任务与首次输入推算"可交互"
const tti = performance.getEntriesByType('navigation')[0].domContentLoadedEventEnd;
new PerformanceObserver((l) => {
const e = l.getEntries()[0];
report('first-input', e.startTime + e.processingStart - e.startTime);
}).observe({ type: 'first-input', buffered: true });
实践中:
- 实验室用 Lighthouse 直接给 TTI。
- 线上用
web-vitals的 INP/TTFB/FCP/LCP 组合评估"可用";TTI 需要自己按"连续 5s 无长任务 + 无未完成请求"规则近似计算。
注意
performance.timing 已被 PerformanceNavigationTiming 取代;跨域资源耗时需服务端配 Timing-Allow-Origin 才能拿到细节。