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

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

## 1. 资源加载优化

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

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

关键点:

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

1.2 资源预加载

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

优化策略:

  • 关键CSS内联到HTML
  • 字体文件使用preconnect+preload
  • 图片使用loading="lazy"属性

2. 渲染性能优化

2.1 减少重排重绘

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

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

container.appendChild(fragment);

最佳实践:

  • 使用CSS transforms替代top/left动画
  • 避免在循环中读取布局属性
  • 使用will-change提示浏览器

2.2 虚拟列表优化

// 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(e.data);
};

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

4. 缓存策略

4.1 Service Worker缓存

// 缓存策略示例
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: "33a64df551425fcc55e4d42a148795d9f25f89d4"

5. 监控与持续优化

5.1 性能指标采集

// 使用Performance API
const [pageNav] = performance.getEntriesByType('navigation');
console.log('TTFB:', pageNav.responseStart - pageNav.requestStart);

5.2 Chrome DevTools使用技巧

  • 使用Coverage标签分析未使用代码
  • Performance面板记录运行时性能
  • Lighthouse生成优化建议

6. 现代API应用

6.1 Intersection Observer

const observer = new IntersectionObserver((entries) => {
  entries.forEach(entry => {
    if (entry.isIntersecting) {
      entry.target.src = entry.target.dataset.src;
      observer.unobserve(entry.target);
    }
  });
});

images.forEach(img => observer.observe(img));

6.2 Web Components优化

class MyElement extends HTMLElement {
  constructor() {
    super();
    this.attachShadow({ mode: 'open' });
  }
  connectedCallback() {
    this.shadowRoot.innerHTML = `<style>/* 作用域样式 */</style>`;
  }
}

7. 构建优化

7.1 Tree Shaking配置

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