性能监控与分析(Performance Monitoring & Analysis)
性能分析工具和方法。
📚 浏览器工具
1. Chrome DevTools
Performance 面板
- 录制性能
- 分析帧率
- 查看主线程活动
- 识别性能瓶颈
Memory 面板
- 堆快照
- 时间线分析
- 内存泄漏检测
Network 面板
- 请求时间分析
- 资源加载优化
- 缓存分析
2. Performance API
Performance.now()
const start = performance.now();
// 执行代码
const end = performance.now();
console.log(`耗时: ${end - start}ms`);Performance.mark()
performance.mark('start');
// 执行代码
performance.mark('end');
performance.measure('duration', 'start', 'end');
const measure = performance.getEntriesByName('duration')[0];
console.log(measure.duration);Performance Observer
const observer = new PerformanceObserver((list) => {
for (const entry of list.getEntries()) {
console.log(entry.name, entry.duration);
}
});
observer.observe({ entryTypes: ['measure', 'mark'] });🎯 性能指标
1. Web Vitals
// LCP (Largest Contentful Paint)
new PerformanceObserver((list) => {
const entries = list.getEntries();
const lastEntry = entries[entries.length - 1];
console.log('LCP:', lastEntry.renderTime);
}).observe({ entryTypes: ['largest-contentful-paint'] });
// FID (First Input Delay)
new PerformanceObserver((list) => {
for (const entry of list.getEntries()) {
console.log('FID:', entry.processingStart - entry.startTime);
}
}).observe({ entryTypes: ['first-input'] });
// CLS (Cumulative Layout Shift)
let clsValue = 0;
new PerformanceObserver((list) => {
for (const entry of list.getEntries()) {
if (!entry.hadRecentInput) {
clsValue += entry.value;
}
}
console.log('CLS:', clsValue);
}).observe({ entryTypes: ['layout-shift'] });2. 自定义指标
// 页面加载时间
window.addEventListener('load', () => {
const loadTime = performance.timing.loadEventEnd - performance.timing.navigationStart;
console.log('页面加载时间:', loadTime);
});
// 首屏渲染时间
const paintEntries = performance.getEntriesByType('paint');
paintEntries.forEach(entry => {
console.log(`${entry.name}:`, entry.startTime);
});💡 性能分析工具
1. Lighthouse
# 命令行
lighthouse https://example.com --view
# Chrome DevTools
# 打开 Lighthouse 面板运行分析2. WebPageTest
在线工具,提供详细的性能分析报告。
3. Bundle Analyzer
// webpack-bundle-analyzer
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
module.exports = {
plugins: [
new BundleAnalyzerPlugin()
]
};🔧 监控实践
1. 性能监控 SDK
class PerformanceMonitor {
constructor() {
this.metrics = {};
this.init();
}
init() {
this.measureLCP();
this.measureFID();
this.measureCLS();
}
measureLCP() {
new PerformanceObserver((list) => {
const entries = list.getEntries();
const lastEntry = entries[entries.length - 1];
this.metrics.lcp = lastEntry.renderTime;
this.report();
}).observe({ entryTypes: ['largest-contentful-paint'] });
}
report() {
// 发送到监控服务
fetch('/api/metrics', {
method: 'POST',
body: JSON.stringify(this.metrics)
});
}
}
new PerformanceMonitor();2. 错误监控
window.addEventListener('error', (event) => {
// 发送错误信息
sendError({
message: event.message,
filename: event.filename,
lineno: event.lineno,
colno: event.colno
});
});🔗 相关链接
参考: