# 前端性能优化实战指南
## 1. 资源加载优化
### 1.1 代码拆分与懒加载
```javascript
// 动态导入实现懒加载
const LazyComponent = React.lazy(() => import('./LazyComponent'));
function MyComponent() {
return (
<Suspense fallback={<div>Loading...</div>}>
<LazyComponent />
</Suspense>
);
}
1.2 资源压缩
- 使用Webpack的TerserPlugin压缩JS
- 配置CSS压缩插件
- 图片使用WebP格式并设置合适的quality参数
1.3 缓存策略
# Nginx配置示例
location /static/ {
expires 1y;
add_header Cache-Control "public";
}
2. 渲染性能优化
2.1 虚拟列表
// React中使用react-window实现虚拟列表
import { FixedSizeList as List } from 'react-window';
const Row = ({ index, style }) => (
<div style={style}>Row {index}</div>
);
const Example = () => (
<List
height={600}
itemCount={1000}
itemSize={35}
width={300}
>
{Row}
</List>
);
2.2 避免强制同步布局
// 错误示例 - 导致强制同步布局
function resizeAllParagraphs() {
for (let i = 0; i < paragraphs.length; i++) {
paragraphs[i].style.width = box.offsetWidth + 'px';
}
}
// 正确示例 - 先读取再写入
function resizeAllParagraphs() {
const width = box.offsetWidth;
for (let i = 0; i < paragraphs.length; i++) {
paragraphs[i].style.width = width + 'px';
}
}
3. JavaScript优化
3.1 防抖与节流
// 防抖实现
function debounce(func, wait) {
let timeout;
return function() {
clearTimeout(timeout);
timeout = setTimeout(() => func.apply(this, arguments), wait);
};
}
// 节流实现
function throttle(func, limit) {
let inThrottle;
return function() {
if (!inThrottle) {
func.apply(this, arguments);
inThrottle = true;
setTimeout(() => inThrottle = false, limit);
}
};
}
3.2 Web Worker
// 主线程
const worker = new Worker('worker.js');
worker.postMessage(data);
worker.onmessage = (e) => {
console.log('Received:', e.data);
};
// worker.js
self.onmessage = (e) => {
const result = heavyComputation(e.data);
self.postMessage(result);
};
4. 网络优化
4.1 HTTP/2
# Nginx启用HTTP/2
server {
listen 443 ssl http2;
server_name example.com;
}
4.2 预加载关键资源
<link rel="preload" href="critical.css" as="style">
<link rel="preload" href="main.js" as="script">
5. 监控与持续优化
5.1 性能指标监控
// 使用Performance API获取关键指标
const timing = performance.timing;
const loadTime = timing.loadEventEnd - timing.navigationStart;
// 使用web-vitals库
import {getCLS, getFID, getLCP} from 'web-vitals';
getCLS(console.log);
getFID(console.log);
getLCP(console.log);
5.2 性能预算
// webpack性能预算配置
module.exports = {
performance: {
maxEntrypointSize: 250000,
maxAssetSize: 250000,
hints: 'warning'
}
};
最佳实践总结
-
关键渲染路径优化:
- 内联关键CSS
- 延迟非关键JS
- 预加载关键资源
-
代码层面优化:
- 避免频繁DOM操作
- 使用事件委托
- 合理使用Web Worker
-
持续监控:
- 建立性能基准
- 设置性能预算
- 定期进行性能审计
-
渐进式优化策略: