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

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

## 1. 资源加载优化

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

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

1.2 资源预加载

<!-- 预加载关键资源 -->
<link rel="preload" href="critical.css" as="style">
<link rel="prefetch" href="next-page.js" as="script">

1.3 图片优化

  • 使用WebP格式替代JPEG/PNG
  • 实现响应式图片:<picture> + <source>组合
  • 懒加载图片:loading="lazy"属性

2. 渲染性能优化

2.1 减少重排重绘

// 批量DOM操作
const fragment = document.createDocumentFragment();
items.forEach(item => {
  const li = document.createElement('li');
  li.textContent = item;
  fragment.appendChild(li);
});
list.appendChild(fragment);

2.2 使用CSS硬件加速

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

2.3 虚拟列表优化长列表

// React中使用react-window
import { FixedSizeList as List } from 'react-window';

<List
  height={600}
  itemCount={1000}
  itemSize={35}
  width={300}
>
  {Row}
</List>

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;
    }
  };
}

3.2 Web Worker处理耗时任务

// 主线程
const worker = new Worker('worker.js');
worker.postMessage(data);

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

4. 缓存策略

4.1 Service Worker缓存

// 注册Service Worker
if ('serviceWorker' in navigator) {
  navigator.serviceWorker.register('/sw.js');
}

// sw.js缓存策略示例
self.addEventListener('fetch', event => {
  event.respondWith(
    caches.match(event.request)
      .then(response => response || fetch(event.request))
  );
});

4.2 HTTP缓存头设置

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

5. 监控与分析

5.1 性能指标采集

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

// 使用web-vitals库
import { getCLS, getFID, getLCP } from 'web-vitals';
getCLS(console.log);
getFID(console.log);
getLCP(console.log);

5.2 Lighthouse自动化测试

# 使用Lighthouse CLI
lighthouse https://example.com --output=html --output-path=./report.html

6. 现代框架优化技巧

6.1 React性能优化

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

// 使用useMemo/useCallback
const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);

6.2 Vue性能优化

// 使用v-once
<div v-once>{{ staticContent }}</div>

// 使用computed属性
computed: {
  filteredList() {
    return this.list.filter(item => item.active);
  }
}

7. 构建优化

7.1 Tree Shaking配置

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

7.2 代码压缩

// 使用TerserPlugin
const Ters