如何提高前端应用的性能?
1. 代码优化
压缩和合并资源
module.exports = {
optimization: {
minimize: true
},
plugins: [
new TerserPlugin()
]
}
按需加载
const LazyComponent = React.lazy(() => import('./LazyComponent'));
减少DOM操作
const fragment = document.createDocumentFragment();
items.forEach(item => {
const li = document.createElement('li');
li.textContent = item;
fragment.appendChild(li);
});
list.appendChild(fragment);
2. 资源优化
图片优化
<img loading="lazy" src="image.webp" alt="示例">
字体优化
@font-face {
font-display: swap;
}
CDN加速
<script src="https://cdn.example.com/library.js"></script>
3. 渲染优化
减少重排重绘
element.style.transform = 'translateX(100px)';
使用虚拟列表
import { FixedSizeList as List } from 'react-window';
<List height={150} itemCount={1000} itemSize={35}>
{Row}
</List>
使用will-change
.animate-element {
will-change: transform;
}
4. 缓存策略
Service Worker
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/sw.js');
}
HTTP缓存头
Cache-Control: max-age=31536000
5. 网络优化
预加载关键资源
<link rel="preload" href="critical.css" as="style">
使用HTTP/2
# Nginx配置HTTP/2
listen 443 ssl http2;
6. 监控与分析
性能指标
const { loadEventEnd, navigationStart } = performance.timing;
const pageLoadTime = loadEventEnd - navigationStart;
Lighthouse审计
npx lighthouse https://example.com
7. 框架优化
React优化
const MemoComponent = React.memo(MyComponent);
Vue优化
<div v-once>{{ staticContent }}</div>
8. 移动端优化
触摸事件优化
element.addEventListener('touchstart', handler, { passive: true });
减少动画复杂度
.animate {
transform: scale(1.2);
opacity: 0.8;
}
9. 安全优化
CSP策略
<meta http-equiv="Content-Security-Policy" content="default-src 'self'">
避免XSS
element.textContent = userInput;
10. 持续优化
A/B测试
if (features.newOptimization) {
}
性能预算
"performance": {
"budgets": {
"resources": "200kb"
}
}