# 前端性能优化实战指南
## 1. 资源加载优化
### 1.1 代码拆分与懒加载
```javascript
// 动态导入实现懒加载
const LazyComponent = React.lazy(() => import('./LazyComponent'));
function App() {
return (
<Suspense fallback={<div>Loading...</div>}>
<LazyComponent />
</Suspense>
);
}
关键点:
- 使用Webpack的SplitChunksPlugin进行代码分割
- 路由级懒加载减少首屏资源体积
- 图片懒加载使用IntersectionObserver API
1.2 资源压缩与CDN加速
# Nginx配置示例
gzip on;
gzip_types text/plain application/xml text/css application/javascript;
gzip_min_length 1000;
最佳实践:
- 静态资源启用Brotli/Gzip压缩
- 关键资源托管到CDN
- 字体文件使用woff2格式
2. 渲染性能优化
2.1 减少重排重绘
// 批量DOM操作
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);
优化策略:
- 使用CSS transform代替top/left动画
- 避免在循环中读取布局属性
- 使用will-change属性提示浏览器
2.2 虚拟列表实现
// React虚拟列表示例
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 = 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(e.data);
};
// worker.js
self.onmessage = (e) => {
const result = heavyCalculation(e.data);
self.postMessage(result);
};
4. 缓存策略
4.1 Service Worker缓存
// 注册Service Worker
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/sw.js')
.then(registration => {
console.log('SW registered');
});
}
// sw.js示例
self.addEventListener('install', (e) => {
e.waitUntil(
caches.open('v1').then((cache) => {
return cache.addAll([
'/',
'/index.html',
'/main.css'
]);
})
);
});
4.2 HTTP缓存头设置
Cache-Control: public, max-age=31536000
ETag: "33a64df551425fcc55e4d42a148795d9f25f89d4"
5. 监控与持续优化
5.1 性能指标采集
// 使用Performance API
const timing = window.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 Lighthouse自动化
// package.json脚本
{
"scripts": {
"audit": "lighthouse http://localhost:3000 --output=html --output-path=./report.html"
}
}
6. 移动端专项优化
6.1 首屏秒开方案
- 服务端渲染(SSR)
- 静态生成(SSG)
- 骨架屏技术
6.2 内存优化
- 避免内存泄漏