perf-web-optimization

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Web Performance Optimization

网页性能优化

Systematic approach: Measure → Identify → Prioritize → Implement → Verify.
系统方法:测量 → 识别 → 排序 → 实施 → 验证。

Target Metrics

目标指标

MetricGoodNeeds WorkPoor
LCP< 2.5s2.5-4s> 4s
INP< 200ms200-500ms> 500ms
CLS< 0.10.1-0.25> 0.25
TTFB< 800ms800ms-1.8s> 1.8s
指标良好待优化较差
LCP< 2.5秒2.5-4秒> 4秒
INP< 200毫秒200-500毫秒> 500毫秒
CLS< 0.10.1-0.25> 0.25
TTFB< 800毫秒800毫秒-1.8秒> 1.8秒

Quick Wins

快速优化方案

1. Images (usually biggest impact on LCP)

1. 图片(通常对LCP影响最大)

html
<!-- Hero/LCP image: eager + high priority -->
<img src="/hero.webp" alt="Hero" width="1200" height="600"
     loading="eager" fetchpriority="high" decoding="async">

<!-- Below fold: lazy load -->
<img src="/product.webp" alt="Product" width="400" height="300"
     loading="lazy" decoding="async">
Always set
width
and
height
to prevent CLS.
html
<!-- Hero/LCP image: eager + high priority -->
<img src="/hero.webp" alt="Hero" width="1200" height="600"
     loading="eager" fetchpriority="high" decoding="async">

<!-- Below fold: lazy load -->
<img src="/product.webp" alt="Product" width="400" height="300"
     loading="lazy" decoding="async">
始终设置
width
height
属性以避免CLS。

2. Fonts (common LCP/CLS culprit)

2. 字体(常见的LCP/CLS影响因素)

html
<!-- Preconnect to font origin -->
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>

<!-- Non-blocking font load -->
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Inter&display=swap"
      media="print" onload="this.media='all'">
html
<!-- Preconnect to font origin -->
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>

<!-- Non-blocking font load -->
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Inter&display=swap"
      media="print" onload="this.media='all'">

3. Third-party Scripts (common INP killer)

3. 第三方脚本(常见的INP性能杀手)

html
<!-- Defer to user interaction -->
<script>
  function loadThirdParty() {
    // Load analytics, chat widgets, etc.
  }
  ['scroll','click','touchstart'].forEach(e =>
    addEventListener(e, loadThirdParty, {once:true, passive:true})
  );
  setTimeout(loadThirdParty, 5000);
</script>
html
<!-- Defer to user interaction -->
<script>
  function loadThirdParty() {
    // Load analytics, chat widgets, etc.
  }
  ['scroll','click','touchstart'].forEach(e =>
    addEventListener(e, loadThirdParty, {once:true, passive:true})
  );
  setTimeout(loadThirdParty, 5000);
</script>

4. Critical CSS

4. 关键CSS

Inline critical CSS in
<head>
, defer the rest:
html
<style>/* critical styles */</style>
<link rel="preload" href="/styles.css" as="style" onload="this.rel='stylesheet'">
将关键CSS内联到
<head>
中,延迟加载其余CSS:
html
<style>/* critical styles */</style>
<link rel="preload" href="/styles.css" as="style" onload="this.rel='stylesheet'">

Bundle Analysis

包分析

bash
undefined
bash
undefined

Webpack

Webpack

npx webpack-bundle-analyzer dist/stats.json
npx webpack-bundle-analyzer dist/stats.json

Vite

Vite

npx vite-bundle-visualizer
npx vite-bundle-visualizer

Check package size before installing

Check package size before installing

npx bundlephobia <package-name>

Common heavy packages to replace:
- `moment` (67KB) → `date-fns` (12KB) or `dayjs` (2KB)
- `lodash` (72KB) → cherry-pick imports or native methods
npx bundlephobia <package-name>

常见需要替换的大体积包:
- `moment`(67KB)→ `date-fns`(12KB)或`dayjs`(2KB)
- `lodash`(72KB)→ 按需导入或使用原生方法

Code Splitting Patterns

代码分割模式

javascript
// React lazy
const Chart = lazy(() => import('./Chart'));

// Next.js dynamic
const Admin = dynamic(() => import('./Admin'), { ssr: false });

// Vite/Rollup manual chunks
build: {
  rollupOptions: {
    output: {
      manualChunks: { vendor: ['react', 'react-dom'] }
    }
  }
}
javascript
// React lazy
const Chart = lazy(() => import('./Chart'));

// Next.js dynamic
const Admin = dynamic(() => import('./Admin'), { ssr: false });

// Vite/Rollup manual chunks
build: {
  rollupOptions: {
    output: {
      manualChunks: { vendor: ['react', 'react-dom'] }
    }
  }
}

Caching Headers

缓存头设置

undefined
undefined

Static assets (immutable hash in filename)

静态资源(文件名包含不可变哈希值)

Cache-Control: public, max-age=31536000, immutable
Cache-Control: public, max-age=31536000, immutable

HTML (revalidate)

HTML(重新验证)

Cache-Control: no-cache
Cache-Control: no-cache

API responses

API响应

Cache-Control: private, max-age=0, must-revalidate
undefined
Cache-Control: private, max-age=0, must-revalidate
undefined

Measurement

性能测量

bash
undefined
bash
undefined

Quick audit

Quick audit

npx lighthouse https://site.com --preset=perf --form-factor=mobile

For running audits, reading reports, and setting budgets, see **perf-lighthouse**.
npx lighthouse https://site.com --preset=perf --form-factor=mobile

如需运行审计、查看报告和设置性能预算,请参考**perf-lighthouse**。

Checklist

检查清单

Images

图片

  • Modern formats (WebP/AVIF)
  • Responsive
    srcset
  • width
    /
    height
    attributes
  • loading="lazy"
    below fold
  • fetchpriority="high"
    on LCP image
  • 现代格式(WebP/AVIF)
  • 响应式
    srcset
  • width
    /
    height
    属性
  • 首屏下方图片设置
    loading="lazy"
  • LCP图片设置
    fetchpriority="high"

JavaScript

JavaScript

  • Bundle < 200KB gzipped
  • Code splitting by route
  • Third-party scripts deferred
  • No unused dependencies
  • 压缩后包体积 < 200KB(gzip)
  • 按路由进行代码分割
  • 第三方脚本延迟加载
  • 移除未使用的依赖

CSS

CSS

  • Critical CSS inlined
  • Non-critical CSS deferred
  • No unused CSS
  • 关键CSS内联
  • 非关键CSS延迟加载
  • 移除未使用的CSS

Fonts

字体

  • font-display: swap
  • Preconnect to font origin
  • Subset if possible
  • 设置
    font-display: swap
  • 预连接字体源
  • 尽可能子集化字体

Detailed Examples

详细示例

For in-depth optimization patterns, see:
  • references/core-web-vitals.md - Fixing LCP, CLS, INP issues
  • references/bundle-optimization.md - Reducing JS bundle size
  • references/image-optimization.md - Image formats, responsive images, sharp scripts
如需深入了解优化模式,请查看:
  • references/core-web-vitals.md - 修复LCP、CLS、INP问题
  • references/bundle-optimization.md - 减小JS包体积
  • references/image-optimization.md - 图片格式、响应式图片、图片压缩脚本