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

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

## 1. 资源加载优化
- **代码分割**:使用Webpack的SplitChunksPlugin进行第三方库分离
```javascript
// webpack.config.js
optimization: {
  splitChunks: {
    chunks: 'all',
    cacheGroups: {
      vendor: {
        test: /[\\/]node_modules[\\/]/,
        name: 'vendors'
      }
    }
  }
}
  • 预加载关键资源
<link rel="preload" href="critical.css" as="style">
<link rel="prefetch" href="next-page.js" as="script">
  • 图片优化
<picture>
  <source srcset="image.webp" type="image/webp">
  <img src="image.jpg" alt="Fallback">
</picture>

2. 渲染性能优化

  • 避免强制同步布局
// 错误示例(导致布局抖动)
function resizeAll() {
  for (let i = 0; i < items.length; i++) {
    items[i].style.width = (items[i].offsetWidth * 2) + 'px';
  }
}

// 正确做法(批量读取后批量写入)
function resizeAll() {
  const widths = items.map(item => item.offsetWidth);
  items.forEach((item, i) => {
    item.style.width = (widths[i] * 2) + 'px';
  });
}
  • 使用will-change优化动画
.animated-element {
  will-change: transform, opacity;
  transition: transform 0.3s ease-out;
}

3. JavaScript优化

  • 防抖节流
// 防抖
function debounce(fn, delay) {
  let timer;
  return function() {
    clearTimeout(timer);
    timer = setTimeout(() => fn.apply(this, arguments), delay);
  };
}

// 节流
function throttle(fn, limit) {
  let lastRun;
  return function() {
    if (!lastRun || Date.now() - lastRun >= limit) {
      fn.apply(this, arguments);
      lastRun = Date.now();
    }
  };
}
  • Web Worker处理密集型任务
// main.js
const worker = new Worker('worker.js');
worker.postMessage(data);
worker.onmessage = (e) => processResult(e.data);

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

4. 缓存策略

  • Service Worker缓存
// sw.js
self.addEventListener('install', (e) => {
  e.waitUntil(
    caches.open('v1').then((cache) => 
      cache.addAll(['/app.js', '/styles.css'])
    )
  );
});

self.addEventListener('fetch', (e) => {
  e.respondWith(
    caches.match(e.request).then((response) => 
      response || fetch(e.request)
    )
  );
});
  • HTTP缓存头设置
Cache-Control: public, max-age=31536000, immutable
ETag: "xyz123"

5. 监控与持续优化

  • 性能指标采集
// 使用Performance API
const [entry] = performance.getEntriesByName('first-contentful-paint');
console.log('FCP:', entry.startTime);

// 使用web-vitals库
import {getCLS, getFID, getLCP} from 'web-vitals';
getCLS(console.log);
getFID(console.log);
getLCP(console.log);
  • 渐进式优化策略
  1. 首屏关键资源控制在14KB以内
  2. 交互时间(TTI)控制在5秒内
  3. 持续监控核心Web指标:
    • LCP < 2.5s
    • FID < 100ms
    • CLS < 0.1

最佳实践总结

  1. 关键渲染路径优化:内联关键CSS,异步加载非关键JS
  2. 资源优化:WebP图片,字体子集,SVG图标
  3. 代码优化:Tree-shaking,懒加载,代码分割
  4. 缓存策略:Service Worker + HTTP缓存组合使用
  5. 持续监控:建立性能预算,设置自动化报警
# 性能检测工具推荐
lighthouse <url> --view
webpack-bundle-analyzer