Appearance
性能测试
性能测试是评估和改进Web应用性能的关键环节,通过系统化的测试方法和工具,可以识别瓶颈、验证优化效果并确保应用始终满足性能标准。
性能指标
核心Web指标 (Core Web Vitals)
Google定义的核心用户体验指标:
- LCP (Largest Contentful Paint):衡量加载性能,目标 < 2.5秒
- FID (First Input Delay):衡量交互性,目标 < 100毫秒
- CLS (Cumulative Layout Shift):衡量视觉稳定性,目标 < 0.1
其他重要指标
- FCP (First Contentful Paint):首次内容绘制
- FP (First Paint):首次绘制
- TTI (Time to Interactive):可交互时间
- TBT (Total Blocking Time):总阻塞时间
测试工具
Lighthouse
Google提供的开源自动化工具:
bash
# 命令行运行
npx lighthouse https://example.com --view
# 在Chrome DevTools中运行
# 开发者工具 -> Lighthouse -> 生成报告
WebPageTest
全面的网站性能测试工具:
- 多地点测试
- 视觉对比
- 详细分析报告
- 影视级可视化
Chrome DevTools
浏览器内置的强大工具:
javascript
// Performance面板录制
performance.mark('start-operation');
// 执行操作
performance.mark('end-operation');
performance.measure('operation', 'start-operation', 'end-operation');
自动化测试
Puppeteer性能测试
javascript
const puppeteer = require('puppeteer');
async function measurePerformance(url) {
const browser = await puppeteer.launch();
const page = await browser.newPage();
// 监听性能指标
await page.evaluateOnNewDocument(() => {
window.performance.mark('start');
});
await page.goto(url);
const metrics = await page.metrics();
const perfTiming = await page.evaluate(() => {
const timing = performance.timing;
return {
dnsLookup: timing.domainLookupEnd - timing.domainLookupStart,
tcpConnect: timing.connectEnd - timing.connectStart,
request: timing.responseEnd - timing.requestStart,
domLoading: timing.domLoading - timing.navigationStart,
loadComplete: timing.loadEventEnd - timing.navigationStart
};
});
await browser.close();
return { metrics, perfTiming };
}
使用Web Vitals库
javascript
import { getCLS, getFID, getLCP, getFCP, getTTFB } from 'web-vitals';
function sendToAnalytics(metric) {
// 发送指标到分析服务
console.log(metric);
}
// 获取核心Web指标
getCLS(sendToAnalytics);
getFID(sendToAnalytics);
getLCP(sendToAnalytics);
getFCP(sendToAnalytics);
getTTFB(sendToAnalytics);
基准测试
设置基准
javascript
// 性能基准测试示例
function benchmarkFunction(fn, iterations = 1000) {
const start = performance.now();
for (let i = 0; i < iterations; i++) {
fn();
}
const end = performance.now();
return {
totalTime: end - start,
avgTime: (end - start) / iterations
};
}
// 使用示例
const result = benchmarkFunction(() => {
// 要测试的函数
heavyCalculation();
});
console.log(`平均执行时间: ${result.avgTime.toFixed(2)}ms`);
加载策略测试
模拟不同网络条件
javascript
// 使用Chrome DevTools协议模拟慢网速
const slowNetwork = {
offline: false,
downloadThroughput: 1.5 * 1024 * 1024 / 8, // 1.5 Mbps
uploadThroughput: 0.75 * 1024 * 1024 / 8, // 0.75 Mbps
latency: 150 // 150ms
};
资源优化测试
图片加载测试
javascript
function testImageLoading(imageUrls) {
const results = [];
for (const url of imageUrls) {
const startTime = performance.now();
const img = new Image();
img.onload = () => {
const endTime = performance.now();
results.push({
url,
loadTime: endTime - startTime,
size: img.naturalWidth * img.naturalHeight
});
};
img.src = url;
}
return results;
}
监控和报告
性能监控仪表板
javascript
// 简单的性能数据收集
class PerformanceMonitor {
constructor() {
this.metrics = {};
}
collectMetrics() {
if ('performance' in window) {
const perfData = performance.getEntriesByType('navigation')[0];
this.metrics = {
loadTime: perfData.loadEventEnd - perfData.fetchStart,
domReady: perfData.domContentLoadedEventEnd - perfData.fetchStart,
firstByte: perfData.responseStart - perfData.requestStart,
domInteractive: perfData.domInteractive - perfData.fetchStart
};
}
}
getMetrics() {
return this.metrics;
}
report() {
console.table(this.metrics);
// 发送到监控服务
}
}
const monitor = new PerformanceMonitor();
window.addEventListener('load', () => {
monitor.collectMetrics();
monitor.report();
});
CI/CD集成
在构建流程中集成性能测试
javascript
// package.json scripts
{
"scripts": {
"perf:test": "lighthouse http://localhost:3000 --only-categories=performance --output=json --output-path=./reports/perf-report.json",
"perf:check": "node scripts/check-performance.js"
}
}
最佳实践
- 建立性能预算并严格执行
- 在真实设备上进行测试
- 模拟真实网络条件
- 定期监控性能变化
- 设置自动化警报
- 将性能指标纳入发布标准