# 前端性能优化实战指南
## 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="prefetch" href="next-page.js" as="script">
1.3 图片优化
- 使用WebP格式替代传统格式
- 实现响应式图片:
<picture>+srcset - 懒加载图片:
loading="lazy"属性
2. 渲染性能优化
2.1 减少重排重绘
// 批量DOM操作
const container = document.getElementById('container');
const fragment = document.createDocumentFragment();
items.forEach(item => {
const el = document.createElement('div');
fragment.appendChild(el);
});
container.appendChild(fragment);
2.2 使用CSS硬件加速
.transform-layer {
transform: translateZ(0);
will-change: transform;
}
2.3 虚拟列表优化长列表
// 使用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>
);
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);
};
}
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 = heavyTask(e.data);
self.postMessage(result);
};
4. 缓存策略
4.1 Service Worker缓存
// 注册Service Worker
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/sw.js');
}
// sw.js示例
self.addEventListener('install', (e) => {
e.waitUntil(
caches.open('v1').then((cache) => {
return cache.addAll([
'/',
'/index.html',
'/styles.css',
'/app.js'
]);
})
);
});
4.2 HTTP缓存头设置
Cache-Control: public, max-age=31536000
ETag: "33a64df551425fcc55e4d42a148795d9f25f89d4"
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 Lighthouse自动化测试
# 使用Lighthouse CLI
lighthouse https://example.com --view --output=html
最佳实践总结
- 关键渲染路径优化:内联关键CSS,异步加载非关键JS
- 资源最小化:使用Tree Shaking、代码压缩、图片压缩
- 现代技术采用:HTTP/2、Brotli压缩、ES模块
- 渐进增强:核心功能优先加载,增强功能延迟加载
- 持续监控:建立性能预算,设置自动化性能测试
通过综合应用这些技术,可以显著提升前端应用的加载速度、交互流畅度和整体