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

47 阅读1分钟

如何提高前端应用的性能

1. 代码优化

1.1 减少JavaScript体积

// 使用Tree Shaking移除未使用代码
import { functionA } from 'module'; 

// 代码分割实现按需加载
const module = await import('./module.js');

1.2 优化CSS

/* 避免过度嵌套 */
.container > .item { ... }

/* 使用CSS变量减少重复 */
:root {
  --primary-color: #4285f4;
}

2. 资源加载优化

2.1 图片优化

<!-- 使用WebP格式 -->
<picture>
  <source srcset="image.webp" type="image/webp">
  <img src="image.jpg" alt="...">
</picture>

2.2 资源预加载

<!-- 关键资源预加载 -->
<link rel="preload" href="main.js" as="script">

3. 渲染优化

3.1 减少重排重绘

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

3.2 使用虚拟滚动

// React示例
import { FixedSizeList } from 'react-window';

4. 缓存策略

4.1 Service Worker缓存

// 注册Service Worker
if ('serviceWorker' in navigator) {
  navigator.serviceWorker.register('/sw.js');
}

4.2 HTTP缓存头

# Nginx配置
location /static {
  expires 1y;
  add_header Cache-Control "public";
}

5. 性能监控

5.1 使用Web Vitals

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

5.2 Lighthouse审计

# 运行Lighthouse测试
lighthouse https://example.com --view

6. 现代API应用

6.1 Intersection Observer

const observer = new IntersectionObserver(callback, options);
observer.observe(element);

6.2 Web Workers

// 主线程
const worker = new Worker('worker.js');
worker.postMessage(data);

7. 构建优化

7.1 使用现代打包工具

// Vite配置示例
export default defineConfig({
  build: {
    minify: 'terser'
  }
});

7.2 代码拆分

// React懒加载
const LazyComponent = React.lazy(() => import('./Component'));

8. 关键优化指标

  1. 首次内容绘制(FCP) < 1.8s
  2. 最大内容绘制(LCP) < 2.5s
  3. 累积布局偏移(CLS) < 0.1
  4. 首次输入延迟(FID) < 100ms

9. 实战技巧

  1. 关键CSS内联
  2. 非关键JS延迟加载
  3. 使用CDN加速静态资源
  4. 启用HTTP/2或HTTP/3
  5. 优化字体加载策略

10. 持续优化流程

  1. 建立性能基准
  2. 设置监控告警
  3. 定期性能审计
  4. A/B测试优化方案
  5. 渐进式优化迭代