如何提高前端应用的性能
1. 代码优化
1.1 减少代码体积
- 使用Tree Shaking移除未使用的代码
- 代码分割(Code Splitting)按需加载
- 使用Webpack等工具进行压缩
optimization: {
splitChunks: {
chunks: 'all'
}
}
1.2 优化JavaScript执行
- 避免长任务阻塞主线程
- 使用Web Workers处理CPU密集型任务
- 合理使用debounce/throttle
2. 网络优化
2.1 减少HTTP请求
- 合并CSS/JS文件
- 使用雪碧图(Sprite)合并小图标
- 内联关键CSS
2.2 资源加载优化
<link rel="preload" href="critical.css" as="style">
<img loading="lazy" src="image.jpg">
3. 渲染优化
3.1 减少重排重绘
- 使用transform/opacity等属性触发GPU加速
- 避免频繁操作DOM
- 使用虚拟列表优化长列表渲染
3.2 优化CSS选择器
4. 缓存策略
4.1 合理配置缓存头
location ~* \.(js|css|png|jpg|jpeg|gif|ico)$ {
expires 1y;
add_header Cache-Control "public, immutable";
}
4.2 使用Service Worker
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/sw.js');
}
5. 性能监控
5.1 使用Lighthouse进行性能评估
npm install -g lighthouse
lighthouse https://example.com
5.2 真实用户监控(RUM)
import {getCLS, getFID, getLCP} from 'web-vitals';
getCLS(console.log);
getFID(console.log);
getLCP(console.log);
6. 现代API应用
6.1 使用Intersection Observer
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
}
});
});
6.2 使用Resize Observer
const resizeObserver = new ResizeObserver(entries => {
for (let entry of entries) {
}
});
7. 图片优化
7.1 选择合适的图片格式
- WebP比JPEG/PNG体积小30%
- 使用响应式图片
<picture>
<source srcset="image.webp" type="image/webp">
<img src="image.jpg" alt="示例图片">
</picture>
7.2 图片压缩
- 使用工具如TinyPNG进行压缩
- 设置合适的图片尺寸
8. 字体优化
8.1 字体子集化
- 只包含需要的字符集
- 使用font-display控制字体加载行为
@font-face {
font-family: 'CustomFont';
src: url('font.woff2') format('woff2');
font-display: swap;
}
9. 构建优化
9.1 使用现代构建工具
- Vite/Esbuild等更快的构建工具
- 升级到Webpack 5
9.2 生产环境优化
- 启用Gzip/Brotli压缩
- 移除console.log等调试代码
10. 持续优化
10.1 性能预算
10.2 A/B测试