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

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

## 1. 资源加载优化

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

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

1.2 资源压缩与CDN

  • 使用Webpack的TerserPlugin压缩JS
  • 配置Gzip/Brotli压缩
  • 静态资源使用CDN加速

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

3. 内存管理

3.1 事件监听清理

useEffect(() => {
  const handleResize = () => {
    // 处理逻辑
  };
  
  window.addEventListener('resize', handleResize);
  
  return () => {
    window.removeEventListener('resize', handleResize);
  };
}, []);

3.2 图片优化

<picture>
  <source srcset="image.webp" type="image/webp">
  <source srcset="image.jpg" type="image/jpeg"> 
  <img src="image.jpg" alt="描述文本">
</picture>

4. 缓存策略

4.1 Service Worker缓存

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

4.2 HTTP缓存头

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

5. 监控与持续优化

5.1 性能指标监控

// 使用Performance API
const [entry] = performance.getEntriesByName('first-contentful-paint');
console.log('FCP:', entry.startTime);

5.2 Lighthouse自动化

// package.json
{
  "scripts": {
    "audit": "lighthouse http://example.com --output=json --output-path=./report.json"
  }
}

最佳实践总结

  1. 关键渲染路径优化

    • 内联关键CSS
    • 延迟非关键JS
    • 预加载重要资源
  2. 代码层面优化

    • 避免深层嵌套组件
    • 合理使用useMemo/useCallback
    • 减少不必要的重新渲染
  3. 网络层面优化

    • 使用HTTP/2
    • 实现资源预连接
    • 优化第三方脚本加载
  4. 持续监控

    • 建立性能基线
    • 设置性能预算
    • 自动化性能测试

通过以上方法的组合应用,可以显著提升前端应用的加载速度和运行时性能,提供更流畅的用户体验。