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

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

## 1. 资源加载优化

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

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

1.2 资源压缩与CDN

  • 使用Webpack的TerserPlugin压缩JS
  • 配置Gzip/Brotli压缩
  • 静态资源部署到CDN

1.3 预加载关键资源

<link rel="preload" href="critical.css" as="style">
<link rel="prefetch" href="next-page.js" as="script">

2. 渲染性能优化

2.1 虚拟列表实现

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

<List
  height={500}
  itemCount={1000}
  itemSize={50}
  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';
  }
}

2.3 使用CSS硬件加速

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

3. 状态管理优化

3.1 精细化状态更新

// 使用React.memo避免不必要渲染
const MemoComponent = React.memo(function MyComponent(props) {
  /* 使用props渲染 */
});

// 使用useMemo缓存计算结果
const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);

3.2 状态管理库选择

  • 轻量级场景:Context + useReducer
  • 复杂场景:Redux Toolkit/Zustand
  • 异步场景:RTK Query/SWR

4. 网络请求优化

4.1 请求合并与缓存

// 使用SWR实现数据缓存
import useSWR from 'swr';

function Profile() {
  const { data, error } = useSWR('/api/user', fetcher);
  // ...
}

4.2 请求优先级控制

// 使用fetch的priority选项
fetch('/api/data', { priority: 'high' });

5. 监控与持续优化

5.1 性能指标监控

// 使用web-vitals库监控核心指标
import { getCLS, getFID, getLCP } from 'web-vitals';

getCLS(console.log);
getFID(console.log);
getLCP(console.log);

5.2 性能预算

// webpack性能预算配置
module.exports = {
  performance: {
    maxEntrypointSize: 512000,
    maxAssetSize: 512000,
    hints: 'warning'
  }
};

6. 移动端专项优化

6.1 首屏加速方案

  • 关键CSS内联
  • 骨架屏占位
  • 图片懒加载

6.2 手势优化

// 使用passive事件监听器
element.addEventListener('touchstart', onTouchStart, { passive: true });

7. 构建优化

7.1 Tree Shaking配置

// webpack生产模式自动启用tree shaking
module.exports = {
  mode: 'production',
  optimization: {
    usedExports: true,
  }
};

7.2 持久化缓存

// webpack缓存配置
module.exports = {
  cache: {
    type: 'filesystem',
    buildDependencies: {
      config: [__filename]
    }
  }
};

8. 图片优化

8.1 现代图片格式