# 前端性能优化实战指南
## 1. 资源加载优化
### 1.1 代码压缩与Tree Shaking
```javascript
// webpack配置示例
module.exports = {
optimization: {
minimize: true,
usedExports: true, // Tree Shaking
},
performance: {
hints: 'warning',
maxAssetSize: 244 * 1024, // 资源大小警告阈值
}
}
1.2 图片优化策略
- 使用WebP格式替代传统格式
- 实现懒加载(Lazy Loading)
- 采用响应式图片(srcset)
- 使用CSS Sprite合并小图标
1.3 缓存策略
# Nginx配置示例
location ~* \.(js|css|png|jpg|jpeg|gif|ico)$ {
expires 30d;
add_header Cache-Control "public, no-transform";
}
2. 渲染性能优化
2.1 减少重排重绘
function updateElements() {
const container = document.getElementById('container');
container.style.display = 'none';
for(let i=0; i<100; i++) {
const div = document.createElement('div');
container.appendChild(div);
}
container.style.display = 'block';
}
2.2 使用虚拟列表
import { FixedSizeList as List } from 'react-window';
const Row = ({ index, style }) => (
<div style={style}>Row {index}</div>
);
const App = () => (
<List
height={600}
itemCount={1000}
itemSize={35}
width={300}
>
{Row}
</List>
);
3. JavaScript执行优化
3.1 防抖与节流
function throttle(fn, delay) {
let lastCall = 0;
return function(...args) {
const now = new Date().getTime();
if(now - lastCall < delay) return;
lastCall = now;
return fn.apply(this, args);
}
}
window.addEventListener('resize', throttle(handleResize, 200));
3.2 Web Worker应用
const worker = new Worker('worker.js');
worker.postMessage({ data: largeArray });
self.onmessage = function(e) {
const result = processData(e.data);
self.postMessage(result);
}
4. 框架级优化
4.1 React性能优化
const MemoComponent = React.memo(function MyComponent(props) {
});
function Parent() {
const memoizedCallback = useCallback(() => {
doSomething(a, b);
}, [a, b]);
return <Child onClick={memoizedCallback} />;
}
4.2 Vue性能优化
const LazyComponent = () => import('./LazyComponent.vue');
<template>
<div v-once>{{ staticContent }}</div>
</template>
5. 监控与持续优化
5.1 性能指标采集
const timing = window.performance.timing;
const loadTime = timing.loadEventEnd - timing.navigationStart;
import {getCLS, getFID, getLCP} from 'web-vitals';
getCLS(console.log);
getFID(console.log);
getLCP(console.log);
5.2 Chrome DevTools技巧
- 使用Performance面板记录运行时性能
- 通过Coverage标签分析未使用代码
- 使用Memory面板检测内存泄漏
- Lighthouse生成全面优化建议
6. 进阶优化方案
6.1 服务端渲染(SSR)
export async function getServerSideProps() {
const data = await fetchData();
return { props: { data } };
}
function Page({ data }) {
return <div>{data