Web前端性能优化实践
1. 关键性能指标
FCP (First Contentful Paint)
首次内容绘制时间,建议控制在2秒以内
TTI (Time to Interactive)
可交互时间,建议控制在3.8秒以内
2. 资源加载优化
2.1 图片优化
2.2 JavaScript优化
const route = {
component: () => import('./views/About.vue')
}
3. 渲染优化
3.1 虚拟列表
// 虚拟列表实现
class VirtualList {
constructor(options) {
this.itemHeight = options.itemHeight;
this.visibleItems = Math.ceil(window.innerHeight / this.itemHeight);
this.startIndex = 0;
this.endIndex = this.startIndex + this.visibleItems;
}
updateVisibleItems(scrollTop) {
this.startIndex = Math.floor(scrollTop / this.itemHeight);
this.endIndex = this.startIndex + this.visibleItems;
this.render();
}
}
3.2 防抖与节流
// 防抖函数
function debounce(fn, delay) {
let timer = null;
return function(...args) {
clearTimeout(timer);
timer = setTimeout(() => {
fn.apply(this, args);
}, delay);
}
}
// 节流函数
function throttle(fn, delay) {
let last = 0;
return function(...args) {
const now = Date.now();
if (now - last > delay) {
fn.apply(this, args);
last = now;
}
}
}
4. 性能优化清单
- 使用CDN加速资源加载
- 启用Gzip压缩
- 合理使用浏览器缓存
- 压缩和合并CSS/JS文件
- 使用字体图标代替图片图标
- 避免重复的HTTP请求
- 优化关键渲染路径
- 使用服务端渲染(SSR)
性能监控
// 性能监控示例
performance.mark('startTask');
// 执行任务
performance.mark('endTask');
performance.measure('taskDuration', 'startTask', 'endTask');
const measures = performance.getEntriesByName('taskDuration');
console.log(`任务耗时: ${measures[0].duration}ms`);