← 返回完整题库
前端性能优化困难

怎么统计页面的性能指标?

参考答案

采集体系

1. 浏览器原生 Performance API

  • performance.timing(旧)/ performance.getEntriesByType('navigation'):DNS、TCP、TTFB、DOMContentLoaded、load 各阶段耗时。
  • performance.getEntriesByType('resource'):每个资源的耗时与体积。
  • performance.now():高精度打点。

2. PerformanceObserver(推荐)

new PerformanceObserver((list) => {
  for (const e of list.getEntries()) report('paint', e);
}).observe({ type: 'paint', buffered: true });

// LCP / CLS / INP 用 web-vitals 更省事
import { onLCP, onCLS, onINP, onTTFB } from 'web-vitals';
onLCP(report); onCLS(report); onINP(report); onTTFB(report);

3. 关键指标计算

  • FCP/LCP:paint 与 largest-contentful-paint 条目 startTime。
  • CLS:累加 layout-shift 中 !hadRecentInput 的 value。
  • INP/FID:first-input 与 event 计时(web-vitals 已实现)。
  • TBT/TTI:需要长任务(longtask)与交互点推算,通常由 Lighthouse 计算。

4. 上报

  • navigator.sendBeacon('/log', JSON.stringify(data)):页面卸载时也能可靠发送。
  • 采样上报(如 10% 用户)+ 分维度聚合,避免日志风暴。
  • 带上 deviceType、网络类型(navigator.connection.effectiveType)、页面版本、地区。

5. 实验室数据
Lighthouse(CI 集成)、WebPageTest(多地域/多网络)、Chrome Performance 面板(火焰图定位瓶颈)。

6. 平台化
自建 RUM 平台或用 Sentry Performance / Datadog RUM / 阿里云 ARMS,做趋势、告警、版本对比。

关键点

  • 指标按 P75/P95 聚合,而非平均。
  • 区分首次访问(冷启动)与二次访问(有缓存)。
  • 采集本身要有性能预算,避免埋点拖慢页面。

本题来自 计算机知识面试题库,共 921 道题。