# 前端性能优化实战指南
## 1. 资源加载优化
### 1.1 代码拆分与懒加载
```javascript
// 动态导入实现懒加载
const LazyComponent = React.lazy(() => import('./LazyComponent'));
1.2 资源压缩与CDN
- 使用Webpack的TerserPlugin压缩JS
- 配置Gzip/Brotli压缩
- 静态资源使用CDN加速
1.3 预加载关键资源
<link rel="preload" href="critical.css" as="style">
<link rel="prefetch" href="next-page.js">
2. 渲染性能优化
2.1 减少重排重绘
// 批量DOM操作
const fragment = document.createDocumentFragment();
items.forEach(item => {
fragment.appendChild(createItemElement(item));
});
container.appendChild(fragment);
2.2 使用虚拟列表
// React中使用react-window
import { FixedSizeList as List } from 'react-window';
<List
height={500}
itemCount={1000}
itemSize={50}
>
{({ index, style }) => <div style={style}>Item {index}</div>}
</List>
2.3 优化CSS选择器
/* 避免 */
.container div:nth-child(3n+1) span {}
/* 推荐 */
.specific-class {}
3. JavaScript优化
3.1 防抖与节流
// 节流实现
function throttle(fn, delay) {
let lastCall = 0;
return function(...args) {
const now = Date.now();
if (now - lastCall >= delay) {
fn.apply(this, args);
lastCall = now;
}
};
}
3.2 Web Worker
// 主线程
const worker = new Worker('worker.js');
worker.postMessage(data);
// worker.js
self.onmessage = function(e) {
const result = heavyComputation(e.data);
self.postMessage(result);
};
3.3 内存管理
// 避免内存泄漏
window.addEventListener('scroll', handleScroll);
// 记得移除
window.removeEventListener('scroll', handleScroll);
4. 网络优化
4.1 HTTP缓存策略
Cache-Control: public, max-age=31536000
ETag: "33a64df551425fcc55e4d42a148795d9f25f89d4"
4.2 服务端渲染(SSR)
// Next.js示例
export async function getServerSideProps() {
const data = await fetchData();
return { props: { data } };
}
4.3 使用HTTP/2
# Nginx配置
listen 443 ssl http2;
5. 监控与持续优化
5.1 性能指标监控
// 使用Web Vitals
import { getCLS, getFID, getLCP } from 'web-vitals';
getCLS(console.log);
getFID(console.log);
getLCP(console.log);
5.2 Lighthouse审计
npm install -g lighthouse
lighthouse https://example.com --view
5.3 性能预算
// package.json
"performance": {
"budgets": [
{
"resourceType": "script",
"budget": 200
}
]
}
最佳实践总结
-
关键渲染路径优化:
- 内联关键CSS
- 异步加载非关键JS
- 预加载关键资源
-
代码层面优化:
- 避免深层嵌套组件
- 合理使用useMemo/useCallback
- 减少不必要的状态更新
-
构建工具配置:
// webpack.config.js module.exports = { optimization: { splitChunks: { chunks: 'all' } } }; -
持续监控:
- 建立性能基准
- 设置性能告警
- 定期进行性能审计
-
渐进式优化策略:
- 首屏优先
- 按需加载
- 优雅降级
通过综合应用这些技术手段,可以显著提升前端应用的性能表现,