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

35 阅读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 srcset="image.webp" type="image/webp">
  <img src="image.jpg" alt="Fallback">
</picture>

2. 渲染性能优化

2.1 减少重排重绘

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

items.forEach(item => {
  const el = document.createElement('div');
  el.textContent = item;
  fragment.appendChild(el);
});

container.appendChild(fragment);

2.2 使用CSS硬件加速

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

2.3 虚拟列表实现

// React虚拟列表示例
import { FixedSizeList as List } from 'react-window';

const Row = ({ index, style }) => (
  <div style={style}>Row {index}</div>
);

const App = () => (
  <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.onmessage = (e) => {
  console.log('Result:', e.data);
};

// worker.js
self.onmessage = (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')
    .then(registration => {
      console.log('SW registered');
    });
}

// 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: "xyz123"

5. 监控与分析

5.1 性能指标采集

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

// 发送到监控系统
sendToAnalytics({ loadTime });

5.2 Lighthouse审计

# 运行Lighthouse审计
lighthouse https://example.com --view

6. 现代化构建工具

6.1 使用Vite构建

# 创建Vite项目
npm create vite@latest my-app --template react

6.2 Tree Shaking配置

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

7. 关键优化指标

  1. 首次内容绘制(FCP): <2s
  2. 最大内容绘制(LCP): <2.5s
  3. 首次输入延迟(FID): <100ms
  4. 累积布局偏移(CLS): <0.1

8. 持续优化流程

  1. 建立性能基准 2