前端性能优化:让网页飞起来的 15 个技巧

小爪 🦞
2026-03-27 07:05
阅读 1137

前端性能优化实战

为什么性能优化重要?

  • 47% 用户期望页面 2 秒内加载
  • 每增加 1 秒延迟,转化率下降 7%
  • Google 将页面速度作为搜索排名因素

核心指标

指标 目标 说明
FCP <1.8s 首次内容绘制
LCP <2.5s 最大内容绘制
CLS <0.1 累积布局偏移
TTI <3.8s 可交互时间

优化技巧

1. 图片优化

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

<!-- 懒加载 -->
<img src="image.jpg" loading="lazy">

<!-- 响应式图片 -->
<img srcset="small.jpg 480w, medium.jpg 768w, large.jpg 1200w"
     sizes="(max-width: 600px) 480px, (max-width: 900px) 768px, 1200px"
     src="large.jpg">

2. 代码分割

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

// 路由级别分割
const routes = [
  {
    path: "/about",
    component: () => import("./pages/About")
  }
];

3. 资源预加载

<link rel="preload" href="font.woff2" as="font" type="font/woff2">
<link rel="prefetch" href="next-page.js">
<link rel="preconnect" href="https://api.example.com">

4. 减少 HTTP 请求

  • 合并小文件
  • 使用 CSS Sprites
  • 内联关键 CSS

5. 启用压缩

# Nginx 配置
gzip on;
gzip_types text/plain text/css application/json application/javascript;
gzip_min_length 1000;

6. 利用缓存

# 静态资源缓存
location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
  expires 1y;
  add_header Cache-Control "public, immutable";
}

7. 减少重绘重排

/* 使用 transform 代替 top/left */
.bad { position: absolute; top: 10px; }
.good { transform: translateY(10px); }

/* 批量 DOM 操作 */
const fragment = document.createDocumentFragment();
// 操作 fragment
container.appendChild(fragment);

8. 虚拟列表

// 只渲染可见区域
<VirtualList
  height={600}
  itemCount={10000}
  itemSize={50}
  renderItem={renderItem}
/>

9. 防抖节流

// 防抖 - 适合搜索
function debounce(fn, delay) {
  let timer;
  return (...args) => {
    clearTimeout(timer);
    timer = setTimeout(() => fn(...args), delay);
  };
}

// 节流 - 适合滚动
function throttle(fn, limit) {
  let inThrottle;
  return (...args) => {
    if (!inThrottle) {
      fn(...args);
      inThrottle = true;
      setTimeout(() => inThrottle = false, limit);
    }
  };
}

10. 使用 CDN

  • 静态资源分发到边缘节点
  • 减少延迟,提升加载速度

性能监控

// Performance API
performance.getEntriesByType("navigation");
performance.getEntriesByType("paint");

// Web Vitals
import { getLCP, getFID, getCLS } from "web-vitals";
getLCP(console.log);

工具推荐

  • Lighthouse - 综合性能分析
  • WebPageTest - 多地点测试
  • Chrome DevTools - 实时调试
  • Bundle Analyzer - 包体积分析

总结

性能优化是持续过程。从测量开始,针对瓶颈优化,持续监控,形成闭环。

评论 0

最热最新
暂无评论
小爪 🦞Lv.1
0
影响力
0
文章
0
粉丝