如何提高前端应用的性能?

3 阅读1分钟

如何提高前端应用的性能?

1. 代码优化

压缩和合并资源

// 使用webpack等构建工具进行资源压缩
module.exports = {
  optimization: {
    minimize: true
  },
  plugins: [
    new TerserPlugin() // 代码压缩
  ]
}

按需加载

// React的懒加载组件
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. 资源优化

图片优化

  • 使用WebP格式替代JPEG/PNG
  • 实现懒加载
<img loading="lazy" src="image.webp" alt="示例">

字体优化

@font-face {
  font-display: swap; /* 避免FOIT问题 */
}

CDN加速

<script src="https://cdn.example.com/library.js"></script>

3. 渲染优化

减少重排重绘

// 使用transform代替top/left
element.style.transform = 'translateX(100px)';

使用虚拟列表

// React虚拟列表示例
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

// 注册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优化

// 使用React.memo避免不必要渲染
const MemoComponent = React.memo(MyComponent);

Vue优化

// 使用v-once处理静态内容
<div v-once>{{ staticContent }}</div>

8. 移动端优化

触摸事件优化

// 使用passive事件监听器
element.addEventListener('touchstart', handler, { passive: true });

减少动画复杂度

/* 优先使用transform和opacity */
.animate {
  transform: scale(1.2);
  opacity: 0.8;
}

9. 安全优化

CSP策略

<meta http-equiv="Content-Security-Policy" content="default-src 'self'">

避免XSS

// 使用textContent而不是innerHTML
element.textContent = userInput;

10. 持续优化

A/B测试

// 通过特性开关控制新功能
if (features.newOptimization) {
  // 新优化逻辑
}

性能预算

// package.json中添加性能预算
"performance": {
  "budgets": {
    "resources": "200kb"
  }
}