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

81 阅读2分钟
# 前端性能优化实战指南

## 1. 资源加载优化
- **代码分割**:使用动态import()实现按需加载
```javascript
// 动态加载组件
const HeavyComponent = React.lazy(() => import('./HeavyComponent'));
  • 预加载关键资源:使用<link rel="preload">提前加载关键CSS/字体
<link rel="preload" href="critical.css" as="style">
  • 图片优化
    • 使用WebP格式(兼容性回退)
    • 响应式图片(srcset)
    • 懒加载(loading="lazy")

2. 渲染性能优化

  • 避免强制同步布局
// 错误示范(导致布局抖动)
function resizeAll() {
  boxes.forEach(box => {
    box.style.width = box.offsetWidth + 10 + 'px';
  });
}

// 正确做法(读写分离)
function resizeAll() {
  const widths = boxes.map(box => box.offsetWidth);
  boxes.forEach((box, i) => {
    box.style.width = widths[i] + 10 + 'px';
  });
}
  • CSS优化
    • 减少选择器复杂度(避免嵌套超过3层)
    • 使用will-change提示浏览器
    • 避免@import(会阻塞渲染)

3. JavaScript优化

  • 防抖/节流处理高频事件:
// 节流实现
function throttle(fn, delay) {
  let lastCall = 0;
  return function(...args) {
    const now = Date.now();
    if (now - lastCall >= delay) {
      fn.apply(this, args);
      lastCall = now;
    }
  };
}
  • Web Worker处理CPU密集型任务:
// 主线程
const worker = new Worker('worker.js');
worker.postMessage(data);

// worker.js
self.onmessage = function(e) {
  const result = heavyComputation(e.data);
  self.postMessage(result);
};

4. 缓存策略

  • Service Worker实现离线缓存:
// 注册Service Worker
if ('serviceWorker' in navigator) {
  navigator.serviceWorker.register('/sw.js');
}

// sw.js示例
self.addEventListener('fetch', event => {
  event.respondWith(
    caches.match(event.request)
      .then(response => response || fetch(event.request))
  );
});
  • HTTP缓存头配置:
Cache-Control: public, max-age=31536000
ETag: "xyz123"

5. 监控与分析

  • 性能指标采集
// 核心Web指标监控
const observer = new PerformanceObserver(list => {
  for (const entry of list.getEntries()) {
    console.log(entry.name, entry.startTime);
  }
});
observer.observe({type: 'largest-contentful-paint'});
  • Chrome DevTools使用技巧
    • Performance面板记录运行时性能
    • Coverage面板分析未使用代码
    • Lighthouse生成优化建议

6. 现代化构建方案

  • Tree Shaking配置:
// webpack.config.js
module.exports = {
  optimization: {
    usedExports: true,
  },
};
  • 代码压缩
    • TerserPlugin压缩JS
    • CSSNano压缩CSS
    • ImageMin插件压缩图片

7. 框架级优化

  • React优化

    • 使用React.memo避免不必要渲染
    • 虚拟列表优化长列表(react-window)
    • 避免内联函数定义
  • Vue优化

    • v-once处理静态内容
    • 合理使用computed属性
    • 组件懒加载

实战建议

  1. 优先解决Lighthouse标红问题
  2. 使用WebPageTest进行多地域测试
  3. 建立性能预算(如JS不超过200KB)
  4. 持续监控(通过RUM工具)