← 返回目录

前端性能优化:加载、渲染与网络策略

高级 · 第 9 篇 ·

性能的核心指标

加载优化

<!-- 预连接关键域名 -->
<link rel="preconnect" href="https://fonts.googleapis.com">

<!-- 预加载关键资源 -->
<link rel="preload" href="/fonts/main.woff2" as="font" type="font/woff2" crossorigin>

<!-- 异步加载非关键 JS -->
<script src="analytics.js" async></script>

<!-- 延迟加载不影响首屏的 JS -->
<script src="widget.js" defer></script>

图片优化

<picture>
  <source srcset="image.avif" type="image/avif">
  <source srcset="image.webp" type="image/webp">
  <img src="image.jpg" alt="图片" loading="lazy">
</picture>

<!-- 指定尺寸避免 CLS -->
<img src="photo.jpg" width="800" height="600" alt="图片">

渲染优化

/* 只动画 transform 和 opacity(GPU 加速) */
.box {
  transition: transform 0.3s, opacity 0.3s;
  will-change: transform;
}

/* 避免动画 width、height、top、left(触发重排) */

网络优化

# Nginx 缓存配置

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

# HTML 文件:协商缓存
location ~* \.html$ {
  add_header Cache-Control "no-cache";
}

# 开启 Gzip/Brotli
gzip on;
gzip_types text/plain text/css application/json application/javascript;

Nginx 部署优化

server {
    listen 80;
    server_name apimp.cn;
    root /var/www/apimp.cn;

    gzip on;
    gzip_types text/html text/css application/javascript;

    location ~* \.(js|css|png|jpg|svg|woff2)$ {
        expires 30d;
        add_header Cache-Control "public, immutable";
    }

    location / {
        try_files $uri $uri/ /index.html;
    }

    # 预留 API 接口转发
    # location /api/ {
    #     proxy_pass http://127.0.0.1:3000;
    # }
}

优化检查清单

  1. HTML 压缩、开启 Gzip/Brotli
  2. 关键 CSS 内联,非关键 CSS 异步加载
  3. JS 文件使用 async/defer
  4. 图片使用 WebP/AVIF 格式,开启 lazy loading
  5. 字体使用 font-display: swap
  6. 静态资源设置长期缓存
  7. 动画只用 transform 和 opacity
  8. 代码分割,按需加载

小结

前端性能优化涵盖加载、渲染、网络三个层面。核心思路:减少资源体积、减少请求次数、减少渲染阻塞、利用浏览器缓存。

下一篇:前端技术架构:模块化、工程化与设计模式