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

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

## 1. 资源加载优化

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

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

关键点:

  • 使用Webpack的代码分割功能
  • 路由级懒加载
  • 组件级懒加载

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

// 正确示例 - 批量读取和写入
function resizeAllParagraphs() {
  const paragraphs = document.querySelectorAll('p');
  const width = box.offsetWidth;
  
  for (let i =  0; i < paragraphs.length; i++) {
    paragraphs[i].style.width = width + 'px';
  }
}

3. 内存管理优化

3.1 事件监听器清理

// React组件中正确清理事件监听器
useEffect(() => {
  const handleResize = () => {
    // 处理逻辑
  };

  window.addEventListener('resize', handleResize);
  
  return () => {
    window.removeEventListener('resize', handleResize);
  };
}, []);

3.2 避免内存泄漏

// 定时器清理示例
useEffect(() => {
  const timer = setInterval(() => {
    // 定时任务
  }, 1000);

  return () => clearInterval(timer);
}, []);

4. 网络请求优化

4.1 请求合并与缓存

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

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

  if (error) return <div>failed to load</div>;
  if (!data) return <div>loading...</div>;
  
  return <div>Hello {data.name}!</div>;
}

4.2 图片优化策略

<!-- 响应式图片示例 -->
<picture>
  <source media="(min-width: 1200px)" srcset="large.jpg">
  <source media="(min-width: 768px)" srcset="medium.jpg">
  <img src="small.jpg" alt="响应式图片">
</picture>

5. 构建优化

5.1 Tree Shaking配置

// webpack.config.js
module.exports = {
  //...
  optimization: {
    usedExports: true,
    minimize: true,
  },
};

5.2 代码压缩与Gzip

# 使用compression-webpack-plugin
npm install compression-webpack-plugin --save-dev

6. 监控与持续优化

6.1 性能指标监控

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

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

6.2 Chrome DevTools使用技巧

  1. 使用Performance面板记录运行时性能
  2. 使用Lighthouse进行综合审计
  3. 使用Coverage面板分析未使用代码
  4. 使用Memory面板检测内存泄漏

7. 移动端专项优化

7