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

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

## 1. 资源加载优化

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

function MyComponent() {
  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中
  • 非关键CSS异步加载
  • 字体文件使用preconnect提前建立连接

2. 渲染性能优化

2.1 虚拟列表优化长列表

// 使用react-window实现虚拟列表
import { FixedSizeList as List } from 'react-window';

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

const Example = () => (
  <List
    height={600}
    itemCount={1000}
    itemSize={35}
    width={300}
  >
    {Row}
  </List>
);

2.2 避免强制同步布局

// 错误示例 - 引起布局抖动
function resizeAllParagraphs() {
  for (let i = 0; i < paragraphs.length; i++) {
    paragraphs[i].style.width = box.offsetWidth + 'px';
  }
}

// 正确做法 - 批量读取后再修改
function resizeAllParagraphs() {
  const width = box.offsetWidth;
  for (let i = 0; i < paragraphs.length; i++) {
    paragraphs[i].style.width = width + 'px';
  }
}

3. JavaScript优化

3.1 防抖与节流

// 防抖实现
function debounce(func, delay) {
  let timer;
  return function() {
    clearTimeout(timer);
    timer = setTimeout(() => func.apply(this, arguments), delay);
  };
}

// 节流实现
function throttle(func, limit) {
  let inThrottle;
  return function() {
    if (!inThrottle) {
      func.apply(this, arguments);
      inThrottle = true;
      setTimeout(() => inThrottle = false, limit);
    }
  };
}

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

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 Chrome DevTools使用技巧

  1. 使用Performance面板记录运行时性能
  2. 通过Cover