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

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

## 1. 资源加载优化

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

1.2 资源压缩

  • 使用Webpack插件压缩资源:
// webpack.config.js
module.exports = {
  plugins: [
    new TerserPlugin(),
    new CssMinimizerPlugin()
  ]
}

1.3 预加载关键资源

<link rel="preload" href="critical.css" as="style">

2. 渲染性能优化

2.1 减少重排重绘

// 批量DOM操作
const fragment = document.createDocumentFragment();
items.forEach(item => {
  fragment.appendChild(createItemElement(item));
});
container.appendChild(fragment);

2.2 使用虚拟列表

// React中使用react-window
import { FixedSizeList as List } from 'react-window';

<List
  height={400}
  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.js
self.onmessage = function(e) {
  const result = heavyCalculation(e.data);
  self.postMessage(result);
}

4. 缓存策略

4.1 Service Worker缓存

// service-worker.js
self.addEventListener('install', (event) => {
  event.waitUntil(
    caches.open('v1').then((cache) => {
      return cache.addAll([
        '/',
        '/index.html',
        '/main.css'
      ]);
    })
  );
});

4.2 HTTP缓存头

Cache-Control: public, max-age=31536000

5. 监控与分析

5.1 性能指标采集

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

5.2 Lighthouse审计

npm install -g lighthouse
lighthouse https://example.com --view

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 MyComponent extends HTMLElement {
  connectedCallback() {
    this.attachShadow({ mode: 'open' });
    this.shadowRoot.innerHTML = `
      <style>
        :host {
          display: block;
        }
      </style>
      <slot></slot>
    `;
  }
}
customElements.define('my-component', MyComponent);

7. 构建优化

7.1 Tree Shaking

// package.json
{
  "sideEffects": false
}

7.2 持久化缓存

// webpack.config.js
module.exports = {
  cache: {
    type: 'filesystem',
    buildDependencies: {
      config: [__filename]
    }
  }
}

8. 网络优化

8.1 HTTP/2推送

Link: </styles.css>; rel=preload; as=style

8.2 资源预连接

<link rel="preconnect" href="https://cdn.example.com">

9. CSS优化

9.1 减少选择器复杂度

/* 避免 */
div.container > ul.list > li.item a.link {}

/* 推荐 */
.link {}

9.2 使用CSS变量

:root {
  --primary-color: #4285f4;