optimize

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese
Identify and fix performance issues to create faster, smoother user experiences.
识别并修复性能问题,打造更流畅、更迅捷的用户体验。

Assess Performance Issues

评估性能问题

Understand current performance and identify problems:
  1. Measure current state:
    • Core Web Vitals: LCP, FID/INP, CLS scores
    • Load time: Time to interactive, first contentful paint
    • Bundle size: JavaScript, CSS, image sizes
    • Runtime performance: Frame rate, memory usage, CPU usage
    • Network: Request count, payload sizes, waterfall
  2. Identify bottlenecks:
    • What's slow? (Initial load? Interactions? Animations?)
    • What's causing it? (Large images? Expensive JavaScript? Layout thrashing?)
    • How bad is it? (Perceivable? Annoying? Blocking?)
    • Who's affected? (All users? Mobile only? Slow connections?)
CRITICAL: Measure before and after. Premature optimization wastes time. Optimize what actually matters.
了解当前性能状况并定位问题:
  1. 衡量当前状态:
    • Core Web Vitals:LCP、FID/INP、CLS 分数
    • 加载时间:可交互时间、首次内容绘制时间
    • 包体积:JavaScript、CSS、图片大小
    • 运行时性能:帧率、内存占用、CPU 使用率
    • 网络情况:请求数量、负载大小、请求瀑布图
  2. 定位性能瓶颈:
    • 哪些环节变慢了?(初始加载?交互操作?动画?)
    • 原因是什么?(图片过大?JavaScript 执行成本高?布局抖动?)
    • 严重程度如何?(用户可感知?造成困扰?阻塞操作?)
    • 影响范围?(所有用户?仅移动端?慢网络环境用户?)
重点提示:优化前后都要进行测量。过早优化只会浪费时间,只针对实际存在的问题进行优化。

Optimization Strategy

优化策略

Create systematic improvement plan:
制定系统化的改进方案:

Loading Performance

加载性能优化

Optimize Images:
  • Use modern formats (WebP, AVIF)
  • Proper sizing (don't load 3000px image for 300px display)
  • Lazy loading for below-fold images
  • Responsive images (
    srcset
    ,
    picture
    element)
  • Compress images (80-85% quality is usually imperceptible)
  • Use CDN for faster delivery
html
<img 
  src="hero.webp"
  srcset="hero-400.webp 400w, hero-800.webp 800w, hero-1200.webp 1200w"
  sizes="(max-width: 400px) 400px, (max-width: 800px) 800px, 1200px"
  loading="lazy"
  alt="Hero image"
/>
Reduce JavaScript Bundle:
  • Code splitting (route-based, component-based)
  • Tree shaking (remove unused code)
  • Remove unused dependencies
  • Lazy load non-critical code
  • Use dynamic imports for large components
javascript
// Lazy load heavy component
const HeavyChart = lazy(() => import('./HeavyChart'));
Optimize CSS:
  • Remove unused CSS
  • Critical CSS inline, rest async
  • Minimize CSS files
  • Use CSS containment for independent regions
Optimize Fonts:
  • Use
    font-display: swap
    or
    optional
  • Subset fonts (only characters you need)
  • Preload critical fonts
  • Use system fonts when appropriate
  • Limit font weights loaded
css
@font-face {
  font-family: 'CustomFont';
  src: url('/fonts/custom.woff2') format('woff2');
  font-display: swap; /* Show fallback immediately */
  unicode-range: U+0020-007F; /* Basic Latin only */
}
Optimize Loading Strategy:
  • Critical resources first (async/defer non-critical)
  • Preload critical assets
  • Prefetch likely next pages
  • Service worker for offline/caching
  • HTTP/2 or HTTP/3 for multiplexing
图片优化:
  • 使用现代格式(WebP、AVIF)
  • 合理设置尺寸(不要为300px的显示区域加载3000px的图片)
  • 对首屏下方的图片启用懒加载
  • 使用响应式图片(
    srcset
    picture
    元素)
  • 压缩图片(通常80-85%的质量不会被用户察觉)
  • 使用CDN加速图片分发
html
<img 
  src="hero.webp"
  srcset="hero-400.webp 400w, hero-800.webp 800w, hero-1200.webp 1200w"
  sizes="(max-width: 400px) 400px, (max-width: 800px) 800px, 1200px"
  loading="lazy"
  alt="Hero image"
/>
缩减JavaScript包体积:
  • 代码分割(基于路由、基于组件)
  • 摇树优化(移除未使用的代码)
  • 删除未使用的依赖
  • 懒加载非核心代码
  • 对大型组件使用动态导入
javascript
// Lazy load heavy component
const HeavyChart = lazy(() => import('./HeavyChart'));
CSS优化:
  • 移除未使用的CSS
  • 核心CSS内联,其余异步加载
  • 最小化CSS文件
  • 对独立区域使用CSS containment
字体优化:
  • 使用
    font-display: swap
    optional
  • 字体子集化(仅包含所需字符)
  • 预加载核心字体
  • 适当使用系统字体
  • 限制加载的字体字重
css
@font-face {
  font-family: 'CustomFont';
  src: url('/fonts/custom.woff2') format('woff2');
  font-display: swap; /* Show fallback immediately */
  unicode-range: U+0020-007F; /* Basic Latin only */
}
加载策略优化:
  • 优先加载核心资源(非核心资源异步/延迟加载)
  • 预加载关键资源
  • 预取可能会访问的下一页资源
  • 使用Service Worker实现离线/缓存功能
  • 使用HTTP/2或HTTP/3实现多路复用

Rendering Performance

渲染性能优化

Avoid Layout Thrashing:
javascript
// ❌ Bad: Alternating reads and writes (causes reflows)
elements.forEach(el => {
  const height = el.offsetHeight; // Read (forces layout)
  el.style.height = height * 2; // Write
});

// ✅ Good: Batch reads, then batch writes
const heights = elements.map(el => el.offsetHeight); // All reads
elements.forEach((el, i) => {
  el.style.height = heights[i] * 2; // All writes
});
Optimize Rendering:
  • Use CSS
    contain
    property for independent regions
  • Minimize DOM depth (flatter is faster)
  • Reduce DOM size (fewer elements)
  • Use
    content-visibility: auto
    for long lists
  • Virtual scrolling for very long lists (react-window, react-virtualized)
Reduce Paint & Composite:
  • Use
    transform
    and
    opacity
    for animations (GPU-accelerated)
  • Avoid animating layout properties (width, height, top, left)
  • Use
    will-change
    sparingly for known expensive operations
  • Minimize paint areas (smaller is faster)
避免布局抖动:
javascript
// ❌ 错误写法:交替读取和写入(会导致重排)
elements.forEach(el => {
  const height = el.offsetHeight; // 读取(强制触发布局)
  el.style.height = height * 2; // 写入
});

// ✅ 正确写法:批量读取,再批量写入
const heights = elements.map(el => el.offsetHeight); // 所有读取操作
elements.forEach((el, i) => {
  el.style.height = heights[i] * 2; // 所有写入操作
});
优化渲染过程:
  • 对独立区域使用CSS
    contain
    属性
  • 最小化DOM层级(结构越扁平越快)
  • 减少DOM元素数量(元素越少越快)
  • 对长列表使用
    content-visibility: auto
  • 对超长列表使用虚拟滚动(react-window、react-virtualized)
减少绘制与合成:
  • 使用
    transform
    opacity
    实现动画(GPU加速)
  • 避免对布局属性(width、height、top、left)执行动画
  • 仅在已知的高成本操作中谨慎使用
    will-change
  • 最小化绘制区域(区域越小越快)

Animation Performance

动画性能优化

GPU Acceleration:
css
/* ✅ GPU-accelerated (fast) */
.animated {
  transform: translateX(100px);
  opacity: 0.5;
}

/* ❌ CPU-bound (slow) */
.animated {
  left: 100px;
  width: 300px;
}
Smooth 60fps:
  • Target 16ms per frame (60fps)
  • Use
    requestAnimationFrame
    for JS animations
  • Debounce/throttle scroll handlers
  • Use CSS animations when possible
  • Avoid long-running JavaScript during animations
Intersection Observer:
javascript
// Efficiently detect when elements enter viewport
const observer = new IntersectionObserver((entries) => {
  entries.forEach(entry => {
    if (entry.isIntersecting) {
      // Element is visible, lazy load or animate
    }
  });
});
GPU加速:
css
/* ✅ GPU加速(高效) */
.animated {
  transform: translateX(100px);
  opacity: 0.5;
}

/* ❌ 依赖CPU(低效) */
.animated {
  left: 100px;
  width: 300px;
}
实现60fps流畅动画:
  • 目标每帧耗时16ms(60fps)
  • 对JS动画使用
    requestAnimationFrame
  • 对滚动事件处理器进行防抖/节流
  • 尽可能使用CSS动画
  • 动画期间避免执行长时间运行的JavaScript
Intersection Observer:
javascript
// 高效检测元素何时进入视口
const observer = new IntersectionObserver((entries) => {
  entries.forEach(entry => {
    if (entry.isIntersecting) {
      // 元素可见,执行懒加载或动画
    }
  });
});

React/Framework Optimization

React/框架优化

React-specific:
  • Use
    memo()
    for expensive components
  • useMemo()
    and
    useCallback()
    for expensive computations
  • Virtualize long lists
  • Code split routes
  • Avoid inline function creation in render
  • Use React DevTools Profiler
Framework-agnostic:
  • Minimize re-renders
  • Debounce expensive operations
  • Memoize computed values
  • Lazy load routes and components
React专属优化:
  • 对性能开销大的组件使用
    memo()
  • 对高成本计算使用
    useMemo()
    useCallback()
  • 对长列表进行虚拟化处理
  • 对路由进行代码分割
  • 避免在render中创建内联函数
  • 使用React DevTools Profiler工具
框架通用优化:
  • 最小化重渲染次数
  • 对高成本操作进行防抖
  • 对计算结果进行 memoize 缓存
  • 懒加载路由和组件

Network Optimization

网络优化

Reduce Requests:
  • Combine small files
  • Use SVG sprites for icons
  • Inline small critical assets
  • Remove unused third-party scripts
Optimize APIs:
  • Use pagination (don't load everything)
  • GraphQL to request only needed fields
  • Response compression (gzip, brotli)
  • HTTP caching headers
  • CDN for static assets
Optimize for Slow Connections:
  • Adaptive loading based on connection (navigator.connection)
  • Optimistic UI updates
  • Request prioritization
  • Progressive enhancement
减少请求数量:
  • 合并小文件
  • 使用SVG雪碧图处理图标
  • 内联小型核心资源
  • 移除未使用的第三方脚本
API优化:
  • 使用分页(不要一次性加载所有内容)
  • 使用GraphQL仅请求所需字段
  • 响应压缩(gzip、brotli)
  • 设置HTTP缓存头
  • 对静态资源使用CDN
针对慢网络环境优化:
  • 根据网络状况进行自适应加载(navigator.connection)
  • 乐观UI更新
  • 请求优先级排序
  • 渐进式增强

Core Web Vitals Optimization

Core Web Vitals 优化

Largest Contentful Paint (LCP < 2.5s)

Largest Contentful Paint (LCP < 2.5s)

  • Optimize hero images
  • Inline critical CSS
  • Preload key resources
  • Use CDN
  • Server-side rendering
  • 优化首屏主图
  • 内联核心CSS
  • 预加载关键资源
  • 使用CDN
  • 服务端渲染

First Input Delay (FID < 100ms) / INP (< 200ms)

First Input Delay (FID < 100ms) / INP (< 200ms)

  • Break up long tasks
  • Defer non-critical JavaScript
  • Use web workers for heavy computation
  • Reduce JavaScript execution time
  • 拆分长任务
  • 延迟加载非核心JavaScript
  • 使用Web Worker处理高成本计算
  • 减少JavaScript执行时间

Cumulative Layout Shift (CLS < 0.1)

Cumulative Layout Shift (CLS < 0.1)

  • Set dimensions on images and videos
  • Don't inject content above existing content
  • Use
    aspect-ratio
    CSS property
  • Reserve space for ads/embeds
  • Avoid animations that cause layout shifts
css
/* Reserve space for image */
.image-container {
  aspect-ratio: 16 / 9;
}
  • 为图片和视频设置尺寸
  • 不要在现有内容上方插入新内容
  • 使用
    aspect-ratio
    CSS属性
  • 为广告/嵌入内容预留空间
  • 避免会导致布局偏移的动画
css
/* 为图片预留空间 */
.image-container {
  aspect-ratio: 16 / 9;
}

Performance Monitoring

性能监控

Tools to use:
  • Chrome DevTools (Lighthouse, Performance panel)
  • WebPageTest
  • Core Web Vitals (Chrome UX Report)
  • Bundle analyzers (webpack-bundle-analyzer)
  • Performance monitoring (Sentry, DataDog, New Relic)
Key metrics:
  • LCP, FID/INP, CLS (Core Web Vitals)
  • Time to Interactive (TTI)
  • First Contentful Paint (FCP)
  • Total Blocking Time (TBT)
  • Bundle size
  • Request count
IMPORTANT: Measure on real devices with real network conditions. Desktop Chrome with fast connection isn't representative.
NEVER:
  • Optimize without measuring (premature optimization)
  • Sacrifice accessibility for performance
  • Break functionality while optimizing
  • Use
    will-change
    everywhere (creates new layers, uses memory)
  • Lazy load above-fold content
  • Optimize micro-optimizations while ignoring major issues (optimize the biggest bottleneck first)
  • Forget about mobile performance (often slower devices, slower connections)
推荐工具:
  • Chrome DevTools(Lighthouse、Performance面板)
  • WebPageTest
  • Core Web Vitals(Chrome UX Report)
  • 包分析工具(webpack-bundle-analyzer)
  • 性能监控平台(Sentry、DataDog、New Relic)
关键指标:
  • LCP、FID/INP、CLS(Core Web Vitals)
  • 可交互时间(TTI)
  • 首次内容绘制(FCP)
  • 总阻塞时间(TBT)
  • 包体积
  • 请求数量
重要提示:在真实设备和真实网络环境下进行测量。桌面端Chrome的快网络环境不具备代表性。
绝对不要:
  • 未测量就进行优化(过早优化)
  • 为了性能牺牲可访问性
  • 优化时破坏原有功能
  • 到处使用
    will-change
    (会创建新图层,占用内存)
  • 对首屏内容进行懒加载
  • 忽略主要问题而去优化微末细节(优先解决最大的性能瓶颈)
  • 忽略移动端性能(通常设备更慢、网络更差)

Verify Improvements

验证优化效果

Test that optimizations worked:
  • Before/after metrics: Compare Lighthouse scores
  • Real user monitoring: Track improvements for real users
  • Different devices: Test on low-end Android, not just flagship iPhone
  • Slow connections: Throttle to 3G, test experience
  • No regressions: Ensure functionality still works
  • User perception: Does it feel faster?
Remember: Performance is a feature. Fast experiences feel more responsive, more polished, more professional. Optimize systematically, measure ruthlessly, and prioritize user-perceived performance.
测试优化是否有效:
  • 前后指标对比:对比Lighthouse分数
  • 真实用户监控:跟踪真实用户的体验提升
  • 多设备测试:在低端Android设备上测试,而不只是旗舰iPhone
  • 慢网络测试:限速到3G,测试体验
  • 无功能回归:确保原有功能正常运行
  • 用户感知:用户是否感觉更快了?
记住:性能是一项功能。迅捷的体验会让产品感觉更响应、更精致、更专业。系统化地进行优化,严格地进行测量,优先关注用户可感知的性能。