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

13 阅读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格式替代传统格式
  • 实现响应式图片(srcset)
  • 懒加载非首屏图片(loading="lazy")

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 使用虚拟列表

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

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
self.addEventListener('install', (e) => {
  e.waitUntil(
    caches.open('v1').then((cache) => {
      return cache.addAll([
        '/',
        '/index.html',
        '/styles/main.css',
        '/scripts/main.js'
      ]);
    })
  );
});

4.2 HTTP缓存头

Cache-Control: public, max-age=31536000
ETag: "33a64df551425fcc55e4d42a148795d9f25f89d4"

5. 监控与分析

5.1 性能指标API

// 测量FP/FCP
const observer = new PerformanceObserver((list) => {
  for (const entry of list.getEntries()) {
    console.log(entry.name, entry.startTime);
  }
});
observer.observe({entryTypes: ['paint']});

// 测量LCP
new PerformanceObserver((entryList) => {
  const entries = entryList.getEntries();
  const lastEntry = entries[entries.length - 1];
  console.log('LCP:', lastEntry.startTime);
}).observe({type: 'largest-contentful-paint', buffered: true});

5.2 Web Vitals监控

import {getCLS, getFID, getLCP} from 'web-vitals';

getCLS(console.log);
getFID(console.log);
getLCP(console.log);

6. 构建优化

6.1 Tree Shaking

// webpack配置
module.exports = {
  mode: 'production',
  optimization: {
    usedExports: true,
  },
};

6.2 代码压缩

// Terser插件配置
const TerserPlugin = require('terser-webpack-plugin');

module.exports = {
  optimization: {
    minimizer: [new TerserPlugin()],
  },
};

7. 网络