性能检测工具
前端常用的性能检测工具和使用方法
问题
前端有哪些性能检测工具?如何使用它们定位性能问题?
解答
1. Chrome DevTools
Performance 面板
// 手动标记性能时间点
performance.mark('start');
// 执行一些操作
for (let i = 0; i < 1000000; i++) {
// 模拟耗时操作
}
performance.mark('end');
// 测量两个标记之间的时间
performance.measure('操作耗时', 'start', 'end');
// 获取测量结果
const measures = performance.getEntriesByType('measure');
console.log(measures[0].duration); // 输出耗时(毫秒)
Network 面板
查看资源加载时间、大小、瀑布流图。
Memory 面板
检测内存泄漏,拍摄堆快照对比。
2. Lighthouse
# 命令行使用
npm install -g lighthouse
lighthouse https://example.com --view
// Node.js 中使用
const lighthouse = require('lighthouse');
const chromeLauncher = require('chrome-launcher');
async function runLighthouse(url) {
const chrome = await chromeLauncher.launch({ chromeFlags: ['--headless'] });
const options = {
logLevel: 'info',
output: 'html',
port: chrome.port
};
const result = await lighthouse(url, options);
console.log('Performance Score:', result.lhr.categories.performance.score * 100);
await chrome.kill();
return result;
}
3. Performance API
// 获取页面加载时间
const timing = performance.timing;
const pageLoadTime = timing.loadEventEnd - timing.navigationStart;
console.log('页面加载时间:', pageLoadTime, 'ms');
// 获取 DNS 查询时间
const dnsTime = timing.domainLookupEnd - timing.domainLookupStart;
// 获取 TCP 连接时间
const tcpTime = timing.connectEnd - timing.connectStart;
// 获取首字节时间 (TTFB)
const ttfb = timing.responseStart - timing.requestStart;
// 获取 DOM 解析时间
const domParseTime = timing.domComplete - timing.domInteractive;
// 使用 PerformanceObserver 监听性能指标
const observer = new PerformanceObserver((list) => {
for (const entry of list.getEntries()) {
console.log(entry.name, entry.startTime, entry.duration);
}
});
// 监听长任务(超过 50ms)
observer.observe({ entryTypes: ['longtask'] });
// 监听资源加载
observer.observe({ entryTypes: ['resource'] });
// 监听最大内容绘制
observer.observe({ entryTypes: ['largest-contentful-paint'] });
4. Web Vitals
import { getCLS, getFID, getLCP, getFCP, getTTFB } from 'web-vitals';
// 核心 Web 指标
getCLS(console.log); // 累积布局偏移
getFID(console.log); // 首次输入延迟
getLCP(console.log); // 最大内容绘制
// 其他指标
getFCP(console.log); // 首次内容绘制
getTTFB(console.log); // 首字节时间
// 上报到分析服务
function sendToAnalytics(metric) {
const body = JSON.stringify({
name: metric.name,
value: metric.value,
id: metric.id
});
// 使用 sendBeacon 确保数据发送
navigator.sendBeacon('/analytics', body);
}
getCLS(sendToAnalytics);
getLCP(sendToAnalytics);
getFID(sendToAnalytics);
5. 自定义性能监控
// 封装性能监控工具
class PerformanceMonitor {
constructor() {
this.metrics = {};
}
// 记录时间点
mark(name) {
this.metrics[name] = performance.now();
}
// 计算耗时
measure(name, startMark, endMark) {
const duration = this.metrics[endMark] - this.metrics[startMark];
console.log(`${name}: ${duration.toFixed(2)}ms`);
return duration;
}
// 监控长任务
observeLongTasks(callback) {
const observer = new PerformanceObserver((list) => {
for (const entry of list.getEntries()) {
callback({
duration: entry.duration,
startTime: entry.startTime
});
}
});
observer.observe({ entryTypes: ['longtask'] });
}
// 获取资源加载信息
getResourceTiming() {
return performance.getEntriesByType('resource').map(entry => ({
name: entry.name,
duration: entry.duration,
size: entry.transferSize,
type: entry.initiatorType
}));
}
}
const monitor = new PerformanceMonitor();
monitor.mark('appStart');
// ... 应用初始化
monitor.mark('appReady');
monitor.measure('应用启动时间', 'appStart', 'appReady');
6. 常用第三方工具
| 工具 | 用途 |
|---|---|
| WebPageTest | 多地点、多浏览器测试 |
| GTmetrix | 综合性能分析 |
| Sentry | 错误和性能监控 |
| New Relic | APM 监控 |
关键点
- Chrome DevTools:Performance 面板录制分析、Memory 检测内存泄漏、Network 查看资源加载
- Lighthouse:自动化审计,输出性能、可访问性、SEO 等评分
- Performance API:
performance.timing获取加载时间,PerformanceObserver监听性能事件 - Web Vitals:关注 LCP(< 2.5s)、FID(< 100ms)、CLS(< 0.1)三个核心指标
- 长任务监控:超过 50ms 的任务会阻塞主线程,需要拆分或放入 Web Worker
目录