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

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

## 1. 资源加载优化

### 1.1 代码拆分与懒加载
```javascript
// 动态导入实现懒加载
const LazyComponent = React.lazy(() => import('./LazyComponent'));

function App() {
  return (
    <Suspense fallback={<Loading />}>
      <LazyComponent />
    </Suspense>
  );
}

关键点:

  • 使用Webpack的SplitChunksPlugin拆分代码
  • 路由级懒加载减少初始包体积
  • 图片懒加载使用IntersectionObserver

1.2 资源预加载

<!-- 关键资源预加载 -->
<link rel="preload" href="critical.css" as="style">
<link rel="prefetch" href="next-page.js" as="script">

2. 渲染性能优化

2.1 虚拟列表

// React实现虚拟列表
import { FixedSizeList as List } from 'react-window';

const Row = ({ index, style }) => (
  <div style={style}>Row {index}</div>
);

const VirtualList = () => (
  <List height={600} itemCount={1000} itemSize={35} width={300}>
    {Row}
  </List>
);

2.2 避免强制同步布局

// 错误示例:强制同步布局
function resizeAllParagraphs() {
  for (let i = 0; i < paragraphs.length; i++) {
    paragraphs[i].style.width = box.offsetWidth + 'px';
  }
}

// 正确做法:批量读取后再写入
function resizeAllParagraphs() {
  const width = box.offsetWidth;
  for (let i =  0; i < paragraphs.length; i++) {
    paragraphs[i].style.width = width + 'px';
  }
}

3. 缓存策略

3.1 Service Worker缓存

// 注册Service Worker
if ('serviceWorker' in navigator) {
  window.addEventListener('load', () => {
    navigator.serviceWorker.register('/sw.js').then(registration => {
      console.log('SW registered');
    });
  });
}

// sw.js示例
const CACHE_NAME = 'v1';
const urlsToCache = ['/', '/styles/main.css'];

self.addEventListener('install', event => {
  event.waitUntil(
    caches.open(CACHE_NAME)
      .then(cache => cache.addAll(urlsToCache))
  );
});

3.2 HTTP缓存头设置

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

4. 代码级优化

4.1 防抖与节流

// 防抖实现
function debounce(func, wait) {
  let timeout;
  return function() {
    clearTimeout(timeout);
    timeout = setTimeout(() => func.apply(this, arguments), wait);
  };
}

// 节流实现
function throttle(func, limit) {
  let inThrottle;
  return function() {
    if (!inThrottle) {
      func.apply(this, arguments);
      inThrottle = true;
      setTimeout(() => inThrottle = false, limit);
    }
  };
}

4.2 Web Worker

// 主线程
const worker = new Worker('worker.js');
worker.postMessage(data);
worker.onmessage = (e) => {
  console.log('Received:', e.data);
};

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

5. 监控与持续优化

5.1 性能指标监控

// 使用Performance API
const timing = window.performance.timing;
const loadTime = timing.loadEventEnd - timing.navigationStart;

// 核心Web指标
const observer = new PerformanceObserver((list) => {
  for (const entry of list.getEntries()) {
    console.log(entry.name, entry.startTime, entry.duration);
  }
});
observer.observe({ entryTypes: ['paint', 'longtask'] });

5.2 渐进式优化策略

  1. 使用Lighthouse识别问题
  2. 建立性能预算
  3. 实施关键优化项
  4. 建立持续监控机制
  5. 定期性能审计

最佳实践总结