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

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

## 1. 资源加载优化

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

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

关键点:

  • 使用Webpack的SplitChunksPlugin进行代码分割
  • 路由级懒加载减少首屏资源体积
  • 非关键资源延迟加载

1.2 资源压缩与缓存

# Nginx配置示例
gzip on;
gzip_types text/plain application/javascript text/css;
expires 1y;
add_header Cache-Control "public, max-age=31536000";

优化策略:

  • 启用Brotli/Gzip压缩
  • 静态资源设置长期缓存
  • 使用内容哈希实现缓存失效

2. 渲染性能优化

2.1 减少重排重绘

// 批量DOM操作
const container = document.getElementById('container');
const fragment = document.createDocumentFragment();

for(let i=0; i<100; i++) {
  const el = document.createElement('div');
  fragment.appendChild(el);
}

container.appendChild(fragment);

优化技巧:

  • 使用CSS transform代替top/left动画
  • 避免频繁读写DOM样式
  • 使用will-change属性提示浏览器

2.2 虚拟列表优化

// 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>
);

长列表优化方案:

  • 只渲染可视区域内的元素
  • 避免全量DOM节点挂载
  • 使用IntersectionObserver实现按需加载

3. JavaScript执行优化

3.1 防抖与节流

// 节流函数实现
function throttle(fn, delay) {
  let lastCall = 0;
  return function(...args) {
    const now = Date.now();
    if(now - lastCall >= delay) {
      fn.apply(this, args);
      lastCall = now;
    }
  }
}

window.addEventListener('resize', throttle(handleResize, 200));

性能敏感操作:

  • 滚动事件处理
  • 窗口resize监听
  • 高频触发的用户输入

3.2 Web Worker应用

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

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

适用场景:

  • 复杂计算任务
  • 大数据处理
  • 避免阻塞UI线程的操作

4. 网络请求优化

4.1 请求合并与缓存

// 请求缓存实现
const cache = new Map();

async function fetchWithCache(url) {
  if(cache.has(url)) {
    return cache.get(url);
  }
  const res = await fetch(url);
  cache.set(url, res);
  return res;
}

优化方案:

  • GraphQL实现数据聚合
  • 本地缓存请求结果
  • 预加载关键资源

4.2 服务端渲染优化

// Next.js页面示例
export async function getServerSideProps() {
  const data = await fetchAPI();
  return { props: { data } };
}

function Page({ data }) {
  return <div>{data}</div>;
}

SSR优化要点:

  • 流式渲染降低TTFB
  • 部分hydration技术
  • 关键CSS内联

5. 监控与持续优化

5.1 性能指标监控

// 使用web-vitals库
import { getCLS, getFID, getLCP } from 'web-vitals';

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

核心指标:

  • LCP (最大内容绘制)
  • FID (首次输入延迟)
  • CLS (布局偏移)

5.