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

50 阅读1分钟
# 前端性能优化实战指南

## 1. 资源加载优化

**图片优化:**
- 使用WebP格式替代JPEG/PNG(节省30-50%体积)
- 实现懒加载:`<img loading="lazy" src="image.jpg">`
- 响应式图片:`<picture>`配合`srcset`

```html
<picture>
  <source srcset="image.webp" type="image/webp">
  <img src="image.jpg" alt="Fallback">
</picture>

代码拆分:

  • 动态导入:import('./module.js').then(module => {...})
  • Webpack的SplitChunksPlugin配置:
optimization: {
  splitChunks: {
    chunks: 'all'
  }
}

2. 渲染性能优化

关键渲染路径:

  • 内联关键CSS(首屏样式)
  • 异步非关键CSS:<link rel="stylesheet" href="non-critical.css" media="print" onload="this.media='all'">
  • 预加载关键资源:<link rel="preload" href="font.woff2" as="font">

GPU加速:

.transform-element {
  will-change: transform;
  transform: translateZ(0);
}

3. JavaScript优化

事件委托:

document.addEventListener('click', (e) => {
  if(e.target.matches('.btn')) {
    // 处理按钮点击
  }
});

防抖/节流:

function debounce(fn, delay) {
  let timer;
  return (...args) => {
    clearTimeout(timer);
    timer = setTimeout(() => fn(...args), delay);
  };
}

4. 缓存策略

Service Worker缓存:

self.addEventListener('fetch', (event) => {
  event.respondWith(
    caches.match(event.request)
      .then(response => response || fetch(event.request))
  );
});

HTTP缓存头:

Cache-Control: public, max-age=31536000
ETag: "33a64df551425fcc55e4d42a148795d9f25f89d4"

5. 监控与持续优化

性能指标采集:

const perfData = {
  FP: performance.getEntriesByName('first-paint')[0].startTime,
  FCP: performance.getEntriesByName('first-contentful-paint')[0].startTime,
  LCP: new PerformanceObserver(() => {}).observe({type: 'largest-contentful-paint'})
};

Chrome DevTools技巧:

  1. 使用Coverage标签分析未使用代码
  2. Performance标签记录运行时性能
  3. Lighthouse生成优化报告

6. 进阶优化手段

Web Worker:

// main.js
const worker = new Worker('worker.js');
worker.postMessage(data);

// worker.js
onmessage = (e) => {
  const result = heavyCalculation(e.data);
  postMessage(result);
};

WASM应用:

WebAssembly.instantiateStreaming(fetch('module.wasm'))
  .then(obj => obj.instance.exports.exported_func());

实施建议

  1. 优先解决Lighthouse报告的"红色项"
  2. 使用WebPageTest进行多地域测试
  3. 建立性能预算(如JS bundle < 200KB)
  4. 自动化性能测试集成CI/CD

最佳实践:从"首屏性能"入手,逐步优化交互体验,最后处理长列表等复杂场景。保持1s内完成关键渲染,3s内完成可交互状态。