Skip to content

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

参考答案:

下面是一些常用的方法和工具:

1. 使用浏览器开发者工具

Chrome DevTools 提供了丰富的性能分析功能:

  • Performance 面板:记录和分析页面的加载和运行过程,包括所有网络请求、JavaScript 执行、布局和绘制时间等。
  • Lighthouse 面板:生成页面性能报告,提供关于加载速度、可访问性、SEO 和最佳实践的评分和建议。
  • Network 面板:监控网络请求,查看每个请求的详细信息,包括加载时间和资源大小。

示例

  1. 打开 Chrome DevTools(按 F12Ctrl+Shift+I)。
  2. 转到 Performance 面板,点击 Record 按钮开始录制性能数据。
  3. 执行页面操作,然后停止录制,查看详细的性能数据。

2. 使用 Web Vitals

Web Vitals 是 Google 提供的性能指标集合,专注于用户体验:

  • Largest Contentful Paint (LCP)
  • First Input Delay (FID)
  • Cumulative Layout Shift (CLS)

示例

  • 可以通过 Chrome DevTools 的 Lighthouse 面板查看 Web Vitals 指标。
  • 使用 Web Vitals JavaScript 库直接在页面上收集和报告这些指标:
    javascript
    import { getCLS, getFID, getLCP } from 'web-vitals';
    
    getCLS(console.log);
    getFID(console.log);
    getLCP(console.log);

3. 使用性能监控工具

Google PageSpeed Insights:分析页面性能并提供优化建议。它基于 Lighthouse 提供报告。

GTmetrix:提供页面性能分析,包括加载时间、页面大小和请求数量。

  • 访问 GTmetrix
  • 输入页面 URL,查看性能评分和详细分析。

4. 使用 Performance API

Performance API 提供了浏览器的低级性能数据,可以用于自定义性能测量:

  • Performance.now():获取自页面加载开始以来的时间(高精度时间戳)。
  • Performance.mark() 和 Performance.measure():标记特定事件,并测量事件之间的时间。

示例

javascript
performance.mark('start');
// 执行某些操作
performance.mark('end');
performance.measure('my-measure', 'start', 'end');
const measure = performance.getEntriesByName('my-measure')[0];
console.log(`Duration: ${measure.duration}ms`);

题目要点:

  • 浏览器开发者工具(如 Chrome DevTools)提供详尽的实时性能数据。
  • Web VitalsLighthouse 提供核心用户体验指标和优化建议。
  • PageSpeed InsightsGTmetrix 提供详细的性能分析报告。
  • Performance API 用于自定义性能测量。