# 前端性能优化实战指南
## 1. 资源加载优化
### 1.1 代码拆分与懒加载
```javascript
// 动态导入实现懒加载
const LazyComponent = React.lazy(() => import('./LazyComponent'));
function MyComponent() {
return (
<Suspense fallback={<div>Loading...</div>}>
<LazyComponent />
</Suspense>
);
}
1.2 资源预加载
<link rel="preload" href="critical.css" as="style">
<link rel="preload" href="main.js" as="script">
1.3 图片优化
- 使用WebP格式替代传统格式
- 实现响应式图片(srcset)
- 懒加载非首屏图片(loading="lazy")
2. 渲染性能优化
2.1 减少重排重绘
const container = document.getElementById('container');
const fragment = document.createDocumentFragment();
for (let i = 0; i < 100; i++) {
const div = document.createElement('div');
fragment.appendChild(div);
}
container.appendChild(fragment);
2.2 使用虚拟列表
import { FixedSizeList as List } from 'react-window';
const Row = ({ index, style }) => (
<div style={style}>Row {index}</div>
);
const VirtualList = () => (
<List
height={500}
itemCount={1000}
itemSize={35}
width={300}
>
{Row}
</List>
);
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.onmessage = (e) => {
console.log('Result:', e.data);
};
self.onmessage = (e) => {
const result = heavyCalculation(e.data);
self.postMessage(result);
};
4. 缓存策略
4.1 Service Worker缓存
self.addEventListener('install', (event) => {
event.waitUntil(
caches.open('v1').then((cache) => {
return cache.addAll([
'/',
'/index.html',
'/styles/main.css',
'/scripts/main.js'
]);
})
);
});
4.2 HTTP缓存头
Cache-Control: public, max-age=31536000
ETag: "33a64df551425fcc55e4d42a148795d9f25f89d4"
5. 监控与分析
5.1 性能指标采集
const timing = performance.timing;
const loadTime = timing.loadEventEnd - timing.navigationStart;
console.log(`Page load time: ${loadTime}ms`);
5.2 Lighthouse审计
lighthouse https://example.com --output=html --output-path=./report.html
6. 现代框架优化技巧
6.1 React性能优化
const MemoComponent = React.memo(function MyComponent(props) {
});
const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);
6.2 Vue优化策略
<div v-once>{{ staticContent }}</div>
computed: {
filteredList() {
return this.list.filter(item => item.active);
}
}
7. 构建优化
7.1 Tree Shaking配置
module.exports = {
mode: 'production',
optimization: {
usedExports: true,
},
};
7