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

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

## 1. 资源加载优化

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

function MyComponent() {
  return (
    <Suspense fallback={<div>Loading...</div>}>
      <LazyComponent />
    </Suspense>
  );
}

1.2 资源压缩

  • 使用Webpack插件压缩资源:
// webpack.config.js
module.exports = {
  plugins: [
    new TerserPlugin(),
    new CssMinimizerPlugin(),
    new ImageMinimizerPlugin()
  ]
}

1.3 CDN加速

<script src="https://cdn.example.com/react@18.2.0/umd/react.production.min.js"></script>

2. 渲染性能优化

2.1 虚拟列表

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

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

const Example = () => (
  <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;
  requestAnimationFrame(() => {
    for (let i = 0; i < paragraphs.length; i++) {
      paragraphs[i].style.width = width + 'px';
    }
  });
}

3. 缓存策略

3.1 Service Worker缓存

// service-worker.js
self.addEventListener('install', (event) => {
  event.waitUntil(
    caches.open('v1').then((cache) => {
      return cache.addAll([
        '/',
        '/index.html',
        '/styles/main.css',
        '/scripts/main.js'
      ]);
    })
  );
});

3.2 HTTP缓存头

Cache-Control: public, max-age=31536000
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 = (e) => {
  const result = heavyComputation(e.data);
  self.postMessage(result);
};

5. 监控与分析

5.1 性能指标

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

// 使用Paint Timing API
performance.getEntriesByType('paint').forEach((entry) => {
  console.log(`${entry.name}: ${entry.startTime}`);
});

5.2 错误监控

// 全局错误捕获
window.addEventListener('error', (event) => {
  const { message, filename, lineno, colno, error } = event;
  // 发送错误日志到服务器
  logError({ message, filename, lineno, colno, stack: error.stack });
});

// Promise错误捕获
window.addEventListener('unhandledrejection', (event) => {
  logError({ reason: event.reason });
});