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

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

## 1. 资源加载优化

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

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

关键点:

  • 使用Webpack的代码分割功能
  • 路由级和组件级懒加载
  • 预加载关键资源

1.2 资源压缩

# 使用Terser压缩JS
terser input.js -o output.min.js

# 使用CSSNano压缩CSS
cssnano input.css output.min.css

优化手段:

  • 启用Gzip/Brotli压缩
  • 图片使用WebP格式
  • SVG图标使用雪碧图

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

优化策略:

  • 使用transform代替top/left动画
  • 避免频繁读写DOM属性
  • 使用will-change提示浏览器

2.2 虚拟列表实现

import { FixedSizeList } from 'react-window';

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

const List = () => (
  <FixedSizeList
    height={500}
    width={300}
    itemSize={50}
    itemCount={1000}
  >
    {Row}
  </FixedSizeList>
);

3. JavaScript优化

3.1 防抖与节流

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

// 节流实现
function throttle(fn, interval) {
  let lastTime = 0;
  return function(...args) {
    const now = Date.now();
    if (now - lastTime >= interval) {
      fn.apply(this, args);
      lastTime = 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缓存

// 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缓存头设置

location /static/ {
  expires 1y;
  add_header Cache-Control "public, immutable";
}

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 https://example.com --output=html --output-path=./report.html

6. 现代化构建方案

6.1 使用Vite构建

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

优势:

  • 原生ES模块开发
  • 闪电般的热更新
  • 按需编译

6.