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

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

## 1. 资源加载优化

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

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

关键点:

  • 使用Webpack的SplitChunksPlugin进行代码拆分
  • 路由级懒加载减少初始包体积
  • 图片懒加载使用IntersectionObserver API

1.2 资源预加载

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

优化策略:

  • 关键CSS内联到HTML头部
  • 字体文件使用preload并设置font-display: swap
  • 第三方脚本异步加载(defer/async)

2. 渲染性能优化

2.1 减少重绘回流

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

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

container.appendChild(fragment);

最佳实践:

  • 使用transform代替top/left动画
  • 避免在循环中读取布局属性(offsetTop等)
  • 复杂动画使用will-change属性

2.2 虚拟列表优化

// React中使用react-window实现虚拟列表
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;
    }
  }
}

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

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

4. 缓存策略

4.1 Service Worker缓存

// service-worker.js
const CACHE_NAME = 'v1';
const urlsToCache = [
  '/',
  '/styles/main.css',
  '/scripts/main.js'
];

self.addEventListener('install', event => {
  event.waitUntil(
    caches.open(CACHE_NAME)
      .then(cache => cache.addAll(urlsToCache))
  );
});

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, immutable
ETag: "33a64df551425fcc55e4d42a148795d9f25f89d4"

5. 监控与持续优化

5.1 性能指标监控

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

// 核心Web指标
const observer = new PerformanceObserver((list) => {
  for(const entry of list.getEntries()) {
    console.log(entry.name, entry.startTime, entry.duration);
  }
});
observer.observe({type: 'largest-contentful-paint', buffered: true});

5.2 渐进式优化策略

  1. 使用Lighthouse进行性能审计
  2. 优先解决影响LCP(最大内容绘制)的问题
  3. 优化CLS(布局偏移)问题
  4. 改善FID(首次输入延迟)

6.