web-performance-optimization

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Web Performance Optimization

Web性能优化

Overview

概述

Help developers optimize website and web application performance to improve user experience, SEO rankings, and conversion rates. This skill provides systematic approaches to measure, analyze, and improve loading speed, runtime performance, and Core Web Vitals metrics.
帮助开发者优化网站和Web应用性能,以提升用户体验、SEO排名和转化率。本技能提供系统化的方法来衡量、分析并改进加载速度、运行时性能以及Core Web Vitals指标。

When to Use This Skill

何时使用本技能

  • Use when website or app is loading slowly
  • Use when optimizing for Core Web Vitals (LCP, FID, CLS)
  • Use when reducing JavaScript bundle size
  • Use when improving Time to Interactive (TTI)
  • Use when optimizing images and assets
  • Use when implementing caching strategies
  • Use when debugging performance bottlenecks
  • Use when preparing for performance audits
  • 当网站或应用加载缓慢时使用
  • 当针对Core Web Vitals(LCP、FID、CLS)进行优化时使用
  • 当需要减小JavaScript包体积时使用
  • 当需要提升交互时间(TTI)时使用
  • 当需要优化图片和资源时使用
  • 当需要实施缓存策略时使用
  • 当需要调试性能瓶颈时使用
  • 当准备进行性能审计时使用

How It Works

工作流程

Step 1: Measure Current Performance

步骤1:衡量当前性能

I'll help you establish baseline metrics:
  • Run Lighthouse audits
  • Measure Core Web Vitals (LCP, FID, CLS)
  • Check bundle sizes
  • Analyze network waterfall
  • Identify performance bottlenecks
我会帮你建立基准指标:
  • 运行Lighthouse审计
  • 测量Core Web Vitals(LCP、FID、CLS)
  • 检查包体积
  • 分析网络瀑布图
  • 识别性能瓶颈

Step 2: Identify Issues

步骤2:定位问题

Analyze performance problems:
  • Large JavaScript bundles
  • Unoptimized images
  • Render-blocking resources
  • Slow server response times
  • Missing caching headers
  • Layout shifts
  • Long tasks blocking main thread
分析性能问题:
  • 过大的JavaScript包
  • 未优化的图片
  • 阻塞渲染的资源
  • 缓慢的服务器响应时间
  • 缺失的缓存头
  • 布局偏移
  • 阻塞主线程的长任务

Step 3: Prioritize Optimizations

步骤3:优先优化项

Focus on high-impact improvements:
  • Critical rendering path optimization
  • Code splitting and lazy loading
  • Image optimization
  • Caching strategies
  • Third-party script optimization
聚焦高影响的改进:
  • 关键渲染路径优化
  • 代码分割与懒加载
  • 图片优化
  • 缓存策略
  • 第三方脚本优化

Step 4: Implement Optimizations

步骤4:实施优化

Apply performance improvements:
  • Optimize assets (images, fonts, CSS, JS)
  • Implement code splitting
  • Add caching headers
  • Lazy load non-critical resources
  • Optimize critical rendering path
应用性能改进措施:
  • 优化资源(图片、字体、CSS、JS)
  • 实施代码分割
  • 添加缓存头
  • 懒加载非关键资源
  • 优化关键渲染路径

Step 5: Verify Improvements

步骤5:验证改进效果

Measure impact of changes:
  • Re-run Lighthouse audits
  • Compare before/after metrics
  • Monitor real user metrics (RUM)
  • Test on different devices and networks
测量变更的影响:
  • 重新运行Lighthouse审计
  • 比较优化前后的指标
  • 监控真实用户指标(RUM)
  • 在不同设备和网络环境下测试

Examples

示例

Example 1: Optimizing Core Web Vitals

示例1:优化Core Web Vitals

markdown
undefined
markdown
undefined

Performance Audit Results

性能审计结果

Current Metrics (Before Optimization)

当前指标(优化前)

  • LCP (Largest Contentful Paint): 4.2s ❌ (should be < 2.5s)
  • FID (First Input Delay): 180ms ❌ (should be < 100ms)
  • CLS (Cumulative Layout Shift): 0.25 ❌ (should be < 0.1)
  • Lighthouse Score: 62/100
  • LCP(Largest Contentful Paint): 4.2s ❌(应小于2.5s)
  • FID(First Input Delay): 180ms ❌(应小于100ms)
  • CLS(Cumulative Layout Shift): 0.25 ❌(应小于0.1)
  • Lighthouse评分: 62/100

Issues Identified

定位的问题

  1. LCP Issue: Hero image (2.5MB) loads slowly
  2. FID Issue: Large JavaScript bundle (850KB) blocks main thread
  3. CLS Issue: Images without dimensions cause layout shifts
  1. LCP问题: 首屏图片(2.5MB)加载缓慢
  2. FID问题: 大型JavaScript包(850KB)阻塞主线程
  3. CLS问题: 未指定尺寸的图片导致布局偏移

Optimization Plan

优化方案

Fix LCP (Largest Contentful Paint)

修复LCP(Largest Contentful Paint)

Problem: Hero image is 2.5MB and loads slowly
Solutions: ```html
<!-- Before: Unoptimized image --> <img src="/hero.jpg" alt="Hero"> <!-- After: Optimized with modern formats --> <picture> <source srcset="/hero.avif" type="image/avif"> <source srcset="/hero.webp" type="image/webp"> <img src="/hero.jpg" alt="Hero" width="1200" height="600" loading="eager" fetchpriority="high" > </picture> \`\`\`
Additional optimizations:
  • Compress image to < 200KB
  • Use CDN for faster delivery
  • Preload hero image:
    <link rel="preload" as="image" href="/hero.avif">
问题: 首屏图片为2.5MB,加载缓慢
解决方案: ```html
<!-- 优化前:未优化的图片 --> <img src="/hero.jpg" alt="Hero"> <!-- 优化后:使用现代格式 --> <picture> <source srcset="/hero.avif" type="image/avif"> <source srcset="/hero.webp" type="image/webp"> <img src="/hero.jpg" alt="Hero" width="1200" height="600" loading="eager" fetchpriority="high" > </picture> \`\`\`
额外优化:
  • 将图片压缩至200KB以下
  • 使用CDN加速交付
  • 预加载首屏图片:
    <link rel="preload" as="image" href="/hero.avif">

Fix FID (First Input Delay)

修复FID(First Input Delay)

Problem: 850KB JavaScript bundle blocks main thread
Solutions:
  1. Code Splitting: ```javascript // Before: Everything in one bundle import { HeavyComponent } from './HeavyComponent'; import { Analytics } from './analytics'; import { ChatWidget } from './chat';
// After: Lazy load non-critical code const HeavyComponent = lazy(() => import('./HeavyComponent')); const ChatWidget = lazy(() => import('./chat'));
// Load analytics after page interactive if (typeof window !== 'undefined') { window.addEventListener('load', () => { import('./analytics').then(({ Analytics }) => { Analytics.init(); }); }); } ```
  1. Remove Unused Dependencies: ```bash
问题: 850KB的JavaScript包阻塞主线程
解决方案:
  1. 代码分割: ```javascript // 优化前:所有代码在一个包中 import { HeavyComponent } from './HeavyComponent'; import { Analytics } from './analytics'; import { ChatWidget } from './chat';
// 优化后:懒加载非关键代码 const HeavyComponent = lazy(() => import('./HeavyComponent')); const ChatWidget = lazy(() => import('./chat'));
// 页面交互后再加载分析脚本 if (typeof window !== 'undefined') { window.addEventListener('load', () => { import('./analytics').then(({ Analytics }) => { Analytics.init(); }); }); } ```
  1. 移除未使用的依赖: ```bash

Analyze bundle

分析包结构

npx webpack-bundle-analyzer
npx webpack-bundle-analyzer

Remove unused packages

移除未使用的包

npm uninstall moment # Use date-fns instead (smaller) npm install date-fns ```
  1. Defer Non-Critical Scripts: ```html
<!-- Before: Blocks rendering --> <script src="/analytics.js"></script> <!-- After: Deferred --> <script src="/analytics.js" defer></script>
```
npm uninstall moment # 使用date-fns替代(体积更小) npm install date-fns ```
  1. 延迟加载非关键脚本: ```html
<!-- 优化前:阻塞渲染 --> <script src="/analytics.js"></script> <!-- 优化后:延迟加载 --> <script src="/analytics.js" defer></script>
```

Fix CLS (Cumulative Layout Shift)

修复CLS(Cumulative Layout Shift)

Problem: Images without dimensions cause layout shifts
Solutions: ```html
<!-- Before: No dimensions --> <img src="/product.jpg" alt="Product"> <!-- After: With dimensions -->
<img src="/product.jpg" alt="Product" width="400" height="300" style="aspect-ratio: 4/3;"
```
For dynamic content: ```css /* Reserve space for content that loads later */ .skeleton-loader { min-height: 200px; background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%); background-size: 200% 100%; animation: loading 1.5s infinite; }
@keyframes loading { 0% { background-position: 200% 0; } 100% { background-position: -200% 0; } } ```
问题: 未指定尺寸的图片导致布局偏移
解决方案: ```html
<!-- 优化前:未指定尺寸 --> <img src="/product.jpg" alt="Product"> <!-- 优化后:指定尺寸 -->
<img src="/product.jpg" alt="Product" width="400" height="300" style="aspect-ratio: 4/3;"
```
针对动态内容: ```css /* 为后续加载的内容预留空间 */ .skeleton-loader { min-height: 200px; background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%); background-size: 200% 100%; animation: loading 1.5s infinite; }
@keyframes loading { 0% { background-position: 200% 0; } 100% { background-position: -200% 0; } } ```

Results After Optimization

优化后结果

  • LCP: 1.8s ✅ (improved by 57%)
  • FID: 45ms ✅ (improved by 75%)
  • CLS: 0.05 ✅ (improved by 80%)
  • Lighthouse Score: 94/100 ✅
undefined
  • LCP: 1.8s ✅(提升57%)
  • FID: 45ms ✅(提升75%)
  • CLS: 0.05 ✅(提升80%)
  • Lighthouse评分: 94/100 ✅
undefined

Example 2: Reducing JavaScript Bundle Size

示例2:减小JavaScript包体积

markdown
undefined
markdown
undefined

Bundle Size Optimization

包体积优化

Current State

当前状态

  • Total Bundle: 850KB (gzipped: 280KB)
  • Main Bundle: 650KB
  • Vendor Bundle: 200KB
  • Load Time (3G): 8.2s
  • 总包体积: 850KB(gzip压缩后:280KB)
  • 主包体积: 650KB
  • 依赖包体积: 200KB
  • 加载时间(3G网络): 8.2s

Analysis

分析

```bash
```bash

Analyze bundle composition

分析包组成

npx webpack-bundle-analyzer dist/stats.json ```
Findings:
  1. Moment.js: 67KB (can replace with date-fns: 12KB)
  2. Lodash: 72KB (using entire library, only need 5 functions)
  3. Unused code: ~150KB of dead code
  4. No code splitting: Everything in one bundle
npx webpack-bundle-analyzer dist/stats.json ```
发现:
  1. Moment.js:67KB(可替换为date-fns:12KB)
  2. Lodash:72KB(导入了整个库,但仅需5个函数)
  3. 未使用代码:约150KB的死代码
  4. 未进行代码分割:所有代码在一个包中

Optimization Steps

优化步骤

1. Replace Heavy Dependencies

1. 替换重型依赖

```bash
```bash

Remove moment.js (67KB) → Use date-fns (12KB)

移除moment.js(67KB)→ 使用date-fns(12KB)

npm uninstall moment npm install date-fns
npm uninstall moment npm install date-fns

Before

优化前

import moment from 'moment'; const formatted = moment(date).format('YYYY-MM-DD');
import moment from 'moment'; const formatted = moment(date).format('YYYY-MM-DD');

After

优化后

import { format } from 'date-fns'; const formatted = format(date, 'yyyy-MM-dd'); ```
Savings: 55KB
import { format } from 'date-fns'; const formatted = format(date, 'yyyy-MM-dd'); ```
节省体积: 55KB

2. Use Lodash Selectively

2. 按需导入Lodash

```javascript // Before: Import entire library (72KB) import _ from 'lodash'; const unique = _.uniq(array);
// After: Import only what you need (5KB) import uniq from 'lodash/uniq'; const unique = uniq(array);
// Or use native methods const unique = [...new Set(array)]; ```
Savings: 67KB
```javascript // 优化前:导入整个库(72KB) import _ from 'lodash'; const unique = _.uniq(array);
// 优化后:仅导入所需部分(5KB) import uniq from 'lodash/uniq'; const unique = uniq(array);
// 或使用原生方法 const unique = [...new Set(array)]; ```
节省体积: 67KB

3. Implement Code Splitting

3. 实施代码分割

```javascript // Next.js example import dynamic from 'next/dynamic';
// Lazy load heavy components const Chart = dynamic(() => import('./Chart'), { loading: () => <div>Loading chart...</div>, ssr: false });
const AdminPanel = dynamic(() => import('./AdminPanel'), { loading: () => <div>Loading...</div> });
// Route-based code splitting (automatic in Next.js) // pages/admin.js - Only loaded when visiting /admin // pages/dashboard.js - Only loaded when visiting /dashboard ```
```javascript // Next.js示例 import dynamic from 'next/dynamic';
// 懒加载重型组件 const Chart = dynamic(() => import('./Chart'), { loading: () => <div>Loading chart...</div>, ssr: false });
const AdminPanel = dynamic(() => import('./AdminPanel'), { loading: () => <div>Loading...</div> });
// 基于路由的代码分割(Next.js自动支持) // pages/admin.js - 仅在访问/admin时加载 // pages/dashboard.js - 仅在访问/dashboard时加载 ```

4. Remove Dead Code

4. 移除死代码

```javascript // Enable tree shaking in webpack.config.js module.exports = { mode: 'production', optimization: { usedExports: true, sideEffects: false } };
// In package.json { "sideEffects": false } ```
```javascript // 在webpack.config.js中启用摇树优化 module.exports = { mode: 'production', optimization: { usedExports: true, sideEffects: false } };
// 在package.json中设置 { "sideEffects": false } ```

5. Optimize Third-Party Scripts

5. 优化第三方脚本

```html
<!-- Before: Loads immediately --> <script src="https://analytics.com/script.js"></script> <!-- After: Load after page interactive --> <script> window.addEventListener('load', () => { const script = document.createElement('script'); script.src = 'https://analytics.com/script.js'; script.async = true; document.body.appendChild(script); }); </script>
```
```html
<!-- 优化前:立即加载 --> <script src="https://analytics.com/script.js"></script> <!-- 优化后:页面交互后加载 --> <script> window.addEventListener('load', () => { const script = document.createElement('script'); script.src = 'https://analytics.com/script.js'; script.async = true; document.body.appendChild(script); }); </script>
```

Results

结果

  • Total Bundle: 380KB ✅ (reduced by 55%)
  • Main Bundle: 180KB ✅
  • Vendor Bundle: 80KB ✅
  • Load Time (3G): 3.1s ✅ (improved by 62%)
undefined
  • 总包体积: 380KB ✅(减少55%)
  • 主包体积: 180KB ✅
  • 依赖包体积: 80KB ✅
  • 加载时间(3G网络): 3.1s ✅(提升62%)
undefined

Example 3: Image Optimization Strategy

示例3:图片优化策略

markdown
undefined
markdown
undefined

Image Optimization

图片优化

Current Issues

当前问题

  • 15 images totaling 12MB
  • No modern formats (WebP, AVIF)
  • No responsive images
  • No lazy loading
  • 15张图片总计12MB
  • 未使用现代格式(WebP、AVIF)
  • 未使用响应式图片
  • 未启用懒加载

Optimization Strategy

优化策略

1. Convert to Modern Formats

1. 转换为现代格式

```bash
```bash

Install image optimization tools

安装图片优化工具

npm install sharp
npm install sharp

Conversion script (optimize-images.js)

转换脚本(optimize-images.js)

const sharp = require('sharp'); const fs = require('fs'); const path = require('path');
async function optimizeImage(inputPath, outputDir) { const filename = path.basename(inputPath, path.extname(inputPath));
// Generate WebP await sharp(inputPath) .webp({ quality: 80 }) .toFile(path.join(outputDir, `${filename}.webp`));
// Generate AVIF (best compression) await sharp(inputPath) .avif({ quality: 70 }) .toFile(path.join(outputDir, `${filename}.avif`));
// Generate optimized JPEG fallback await sharp(inputPath) .jpeg({ quality: 80, progressive: true }) .toFile(path.join(outputDir, `${filename}.jpg`)); }
// Process all images const images = fs.readdirSync('./images'); images.forEach(img => { optimizeImage(`./images/${img}`, './images/optimized'); }); ```
const sharp = require('sharp'); const fs = require('fs'); const path = require('path');
async function optimizeImage(inputPath, outputDir) { const filename = path.basename(inputPath, path.extname(inputPath));
// 生成WebP格式 await sharp(inputPath) .webp({ quality: 80 }) .toFile(path.join(outputDir, `${filename}.webp`));
// 生成AVIF格式(最优压缩) await sharp(inputPath) .avif({ quality: 70 }) .toFile(path.join(outputDir, `${filename}.avif`));
// 生成优化后的JPEG兜底格式 await sharp(inputPath) .jpeg({ quality: 80, progressive: true }) .toFile(path.join(outputDir, `${filename}.jpg`)); }
// 处理所有图片 const images = fs.readdirSync('./images'); images.forEach(img => { optimizeImage(`./images/${img}`, './images/optimized'); }); ```

2. Implement Responsive Images

2. 实现响应式图片

```html
<!-- Responsive images with modern formats --> <picture> <!-- AVIF for browsers that support it (best compression) --> <source srcset=" /images/hero-400.avif 400w, /images/hero-800.avif 800w, /images/hero-1200.avif 1200w " type="image/avif" sizes="(max-width: 768px) 100vw, 50vw" > <!-- WebP for browsers that support it -->
<source srcset=" /images/hero-400.webp 400w, /images/hero-800.webp 800w, /images/hero-1200.webp 1200w " type="image/webp" sizes="(max-width: 768px) 100vw, 50vw"
<!-- JPEG fallback -->
<img src="/images/hero-800.jpg" srcset=" /images/hero-400.jpg 400w, /images/hero-800.jpg 800w, /images/hero-1200.jpg 1200w " sizes="(max-width: 768px) 100vw, 50vw" alt="Hero image" width="1200" height="600" loading="lazy"
</picture> \`\`\`
```html
<!-- 支持现代格式的响应式图片 --> <picture> <!-- 支持AVIF的浏览器(最优压缩) --> <source srcset=" /images/hero-400.avif 400w, /images/hero-800.avif 800w, /images/hero-1200.avif 1200w " type="image/avif" sizes="(max-width: 768px) 100vw, 50vw" > <!-- 支持WebP的浏览器 -->
<source srcset=" /images/hero-400.webp 400w, /images/hero-800.webp 800w, /images/hero-1200.webp 1200w " type="image/webp" sizes="(max-width: 768px) 100vw, 50vw"
<!-- JPEG兜底格式 -->
<img src="/images/hero-800.jpg" srcset=" /images/hero-400.jpg 400w, /images/hero-800.jpg 800w, /images/hero-1200.jpg 1200w " sizes="(max-width: 768px) 100vw, 50vw" alt="Hero image" width="1200" height="600" loading="lazy"
</picture> \`\`\`

3. Lazy Loading

3. 懒加载

```html
<!-- Native lazy loading -->
<img src="/image.jpg" alt="Description" loading="lazy" width="800" height="600"
<!-- Eager loading for above-the-fold images -->
<img src="/hero.jpg" alt="Hero" loading="eager" fetchpriority="high"
```
```html
<!-- 原生懒加载 -->
<img src="/image.jpg" alt="Description" loading="lazy" width="800" height="600"
<!-- 首屏图片立即加载 -->
<img src="/hero.jpg" alt="Hero" loading="eager" fetchpriority="high"
```

4. Next.js Image Component

4. Next.js Image组件

```javascript import Image from 'next/image';
// Automatic optimization <Image src="/hero.jpg" alt="Hero" width={1200} height={600} priority // For above-the-fold images quality={80} />
// Lazy loaded <Image src="/product.jpg" alt="Product" width={400} height={300} loading="lazy" /> ```
```javascript import Image from 'next/image';
// 自动优化 <Image src="/hero.jpg" alt="Hero" width={1200} height={600} priority // 首屏图片 quality={80} />
// 懒加载 <Image src="/product.jpg" alt="Product" width={400} height={300} loading="lazy" /> ```

Results

结果

MetricBeforeAfterImprovement
Total Image Size12MB1.8MB85% reduction
LCP4.5s1.6s64% faster
Page Load (3G)18s4.2s77% faster
undefined
指标优化前优化后提升幅度
图片总大小12MB1.8MB减少85%
LCP4.5s1.6s提升64%
页面加载时间(3G)18s4.2s提升77%
undefined

Best Practices

最佳实践

✅ Do This

✅ 推荐做法

  • Measure First - Always establish baseline metrics before optimizing
  • Use Lighthouse - Run audits regularly to track progress
  • Optimize Images - Use modern formats (WebP, AVIF) and responsive images
  • Code Split - Break large bundles into smaller chunks
  • Lazy Load - Defer non-critical resources
  • Cache Aggressively - Set proper cache headers for static assets
  • Minimize Main Thread Work - Keep JavaScript execution under 50ms chunks
  • Preload Critical Resources - Use
    <link rel="preload">
    for critical assets
  • Use CDN - Serve static assets from CDN for faster delivery
  • Monitor Real Users - Track Core Web Vitals from real users
  • 先测量再优化 - 优化前务必建立基准指标
  • 使用Lighthouse - 定期运行审计以跟踪进度
  • 优化图片 - 使用现代格式(WebP、AVIF)和响应式图片
  • 代码分割 - 将大包拆分为更小的代码块
  • 懒加载 - 延迟加载非关键资源
  • 积极缓存 - 为静态资源设置合适的缓存头
  • 最小化主线程工作 - 保持JavaScript执行时间在50ms以内的片段
  • 预加载关键资源 - 使用
    <link rel="preload">
    加载关键资源
  • 使用CDN - 通过CDN交付静态资源以加速加载
  • 监控真实用户 - 跟踪真实用户的Core Web Vitals指标

❌ Don't Do This

❌ 不推荐做法

  • Don't Optimize Blindly - Measure first, then optimize
  • Don't Ignore Mobile - Test on real mobile devices and slow networks
  • Don't Block Rendering - Avoid render-blocking CSS and JavaScript
  • Don't Load Everything Upfront - Lazy load non-critical resources
  • Don't Forget Dimensions - Always specify image width/height
  • Don't Use Synchronous Scripts - Use async or defer attributes
  • Don't Ignore Third-Party Scripts - They often cause performance issues
  • Don't Skip Compression - Always compress and minify assets
  • 盲目优化 - 先测量,再优化
  • 忽略移动端 - 在真实移动设备和慢速网络上测试
  • 阻塞渲染 - 避免使用阻塞渲染的CSS和JavaScript
  • 一次性加载所有资源 - 懒加载非关键资源
  • 忘记指定尺寸 - 务必指定图片的宽高
  • 使用同步脚本 - 使用async或defer属性
  • 忽略第三方脚本 - 它们通常会导致性能问题
  • 跳过压缩 - 务必压缩和混淆资源

Common Pitfalls

常见陷阱

Problem: Optimized for Desktop but Slow on Mobile

问题:桌面端优化良好但移动端缓慢

Symptoms: Good Lighthouse score on desktop, poor on mobile Solution:
  • Test on real mobile devices
  • Use Chrome DevTools mobile throttling
  • Optimize for 3G/4G networks
  • Reduce JavaScript execution time
bash
undefined
症状: 桌面端Lighthouse评分高,但移动端表现差 解决方案:
  • 在真实移动设备上测试
  • 使用Chrome DevTools的移动端节流功能
  • 针对3G/4G网络优化
  • 减少JavaScript执行时间
bash
undefined

Test with throttling

启用节流测试

lighthouse https://yoursite.com --throttling.cpuSlowdownMultiplier=4
undefined
lighthouse https://yoursite.com --throttling.cpuSlowdownMultiplier=4
undefined

Problem: Large JavaScript Bundle

问题:JavaScript包体积过大

Symptoms: Long Time to Interactive (TTI), high FID Solution:
  • Analyze bundle with webpack-bundle-analyzer
  • Remove unused dependencies
  • Implement code splitting
  • Lazy load non-critical code
bash
undefined
症状: 交互时间(TTI)长,FID值高 解决方案:
  • 使用webpack-bundle-analyzer分析包结构
  • 移除未使用的依赖
  • 实施代码分割
  • 懒加载非关键代码
bash
undefined

Analyze bundle

分析包结构

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

Problem: Images Causing Layout Shifts

问题:图片导致布局偏移

Symptoms: High CLS score, content jumping Solution:
  • Always specify width and height
  • Use aspect-ratio CSS property
  • Reserve space with skeleton loaders
css
img {
  aspect-ratio: 16 / 9;
  width: 100%;
  height: auto;
}
症状: CLS分数高,内容跳动 解决方案:
  • 务必指定宽高
  • 使用CSS的aspect-ratio属性
  • 使用骨架屏为内容预留空间
css
img {
  aspect-ratio: 16 / 9;
  width: 100%;
  height: auto;
}

Problem: Slow Server Response Time

问题:服务器响应时间缓慢

Symptoms: High TTFB (Time to First Byte) Solution:
  • Implement server-side caching
  • Use CDN for static assets
  • Optimize database queries
  • Consider static site generation (SSG)
javascript
// Next.js: Static generation
export async function getStaticProps() {
  const data = await fetchData();
  return {
    props: { data },
    revalidate: 60 // Regenerate every 60 seconds
  };
}
症状: 首字节时间(TTFB)高 解决方案:
  • 实施服务器端缓存
  • 使用CDN交付静态资源
  • 优化数据库查询
  • 考虑静态站点生成(SSG)
javascript
// Next.js:静态生成
export async function getStaticProps() {
  const data = await fetchData();
  return {
    props: { data },
    revalidate: 60 // 每60秒重新生成
  };
}

Performance Checklist

性能检查清单

Images

图片

  • Convert to modern formats (WebP, AVIF)
  • Implement responsive images
  • Add lazy loading
  • Specify dimensions (width/height)
  • Compress images (< 200KB each)
  • Use CDN for delivery
  • 转换为现代格式(WebP、AVIF)
  • 实现响应式图片
  • 启用懒加载
  • 指定尺寸(宽/高)
  • 压缩图片(单张小于200KB)
  • 使用CDN交付

JavaScript

JavaScript

  • Bundle size < 200KB (gzipped)
  • Implement code splitting
  • Lazy load non-critical code
  • Remove unused dependencies
  • Minify and compress
  • Use async/defer for scripts
  • 包体积小于200KB(gzip压缩后)
  • 实施代码分割
  • 懒加载非关键代码
  • 移除未使用的依赖
  • 混淆和压缩代码
  • 为脚本使用async/defer

CSS

CSS

  • Inline critical CSS
  • Defer non-critical CSS
  • Remove unused CSS
  • Minify CSS files
  • Use CSS containment
  • 内联关键CSS
  • 延迟加载非关键CSS
  • 移除未使用的CSS
  • 混淆CSS文件
  • 使用CSS containment

Caching

缓存

  • Set cache headers for static assets
  • Implement service worker
  • Use CDN caching
  • Cache API responses
  • Version static assets
  • 为静态资源设置缓存头
  • 实现Service Worker
  • 使用CDN缓存
  • 缓存API响应
  • 为静态资源添加版本号

Core Web Vitals

Core Web Vitals

  • LCP < 2.5s
  • FID < 100ms
  • CLS < 0.1
  • TTFB < 600ms
  • TTI < 3.8s
  • LCP < 2.5s
  • FID < 100ms
  • CLS < 0.1
  • TTFB < 600ms
  • TTI < 3.8s

Performance Tools

性能工具

Measurement Tools

测量工具

  • Lighthouse - Comprehensive performance audit
  • WebPageTest - Detailed waterfall analysis
  • Chrome DevTools - Performance profiling
  • PageSpeed Insights - Real user metrics
  • Web Vitals Extension - Monitor Core Web Vitals
  • Lighthouse - 全面的性能审计工具
  • WebPageTest - 详细的网络瀑布图分析
  • Chrome DevTools - 性能分析
  • PageSpeed Insights - 真实用户指标
  • Web Vitals Extension - 监控Core Web Vitals

Analysis Tools

分析工具

  • webpack-bundle-analyzer - Visualize bundle composition
  • source-map-explorer - Analyze bundle size
  • Bundlephobia - Check package sizes before installing
  • ImageOptim - Image compression tool
  • webpack-bundle-analyzer - 可视化包组成
  • source-map-explorer - 分析包体积
  • Bundlephobia - 安装前检查包大小
  • ImageOptim - 图片压缩工具

Monitoring Tools

监控工具

  • Google Analytics - Track Core Web Vitals
  • Sentry - Performance monitoring
  • New Relic - Application performance monitoring
  • Datadog - Real user monitoring
  • Google Analytics - 跟踪Core Web Vitals
  • Sentry - 性能监控
  • New Relic - 应用性能监控
  • Datadog - 真实用户监控

Related Skills

相关技能

  • @react-best-practices
    - React performance patterns
  • @frontend-dev-guidelines
    - Frontend development standards
  • @systematic-debugging
    - Debug performance issues
  • @senior-architect
    - Architecture for performance
  • @react-best-practices
    - React性能模式
  • @frontend-dev-guidelines
    - 前端开发标准
  • @systematic-debugging
    - 调试性能问题
  • @senior-architect
    - 性能导向的架构设计

Additional Resources

额外资源


Pro Tip: Focus on Core Web Vitals (LCP, FID, CLS) first - they have the biggest impact on user experience and SEO rankings!

专业提示: 优先关注Core Web Vitals(LCP、FID、CLS)——它们对用户体验和SEO排名的影响最大!