optimize
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseIdentify and fix performance issues to create faster, smoother user experiences.
识别并修复性能问题,打造更快速、流畅的用户体验。
Assess Performance Issues
评估性能问题
Understand current performance and identify problems:
-
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
-
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.
了解当前性能状况并定位问题:
-
测量当前状态:
- Core Web Vitals: LCP、FID/INP、CLS 分数
- 加载时间: 可交互时间、首次内容绘制时间
- 包体积: JavaScript、CSS、图片大小
- 运行时性能: 帧率、内存占用、CPU 使用率
- 网络: 请求数量、负载大小、瀑布流图
-
定位性能瓶颈:
- 哪些环节缓慢?(初始加载?交互操作?动画?)
- 原因是什么?(图片过大?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 (,
srcsetelement)picture - 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 or
font-display: swapoptional - 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包体积:
- 代码分割(基于路由、基于组件)
- Tree Shaking(移除未使用的代码)
- 删除未使用的依赖
- 懒加载非关键代码
- 对大型组件使用动态导入
javascript
// Lazy load heavy component
const HeavyChart = lazy(() => import('./HeavyChart'));优化CSS:
- 移除未使用的CSS
- 关键CSS内联,其余异步加载
- 最小化CSS文件
- 对独立区域使用CSS containment
优化字体:
- 使用 或
font-display: swapoptional - 子集化字体(仅包含所需字符)
- 预加载关键字体
- 适当使用系统字体
- 限制加载的字体字重
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 */
}优化加载策略:
- 优先加载关键资源(非关键资源使用async/defer)
- 预加载关键资源
- 预取可能访问的下一页
- 使用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 property for independent regions
contain - Minimize DOM depth (flatter is faster)
- Reduce DOM size (fewer elements)
- Use for long lists
content-visibility: auto - Virtual scrolling for very long lists (react-window, react-virtualized)
Reduce Paint & Composite:
- Use and
transformfor animations (GPU-accelerated)opacity - Avoid animating layout properties (width, height, top, left)
- Use sparingly for known expensive operations
will-change - Minimize paint areas (smaller is faster)
避免布局抖动:
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
});优化渲染:
- 对独立区域使用CSS 属性
contain - 最小化DOM层级(结构越扁平越快)
- 减小DOM大小(元素越少越好)
- 对长列表使用
content-visibility: auto - 对超长列表使用虚拟滚动(react-window、react-virtualized)
减少绘制与合成:
- 使用 和
transform实现动画(GPU加速)opacity - 避免对布局属性(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 for JS animations
requestAnimationFrame - 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-accelerated (fast) */
.animated {
transform: translateX(100px);
opacity: 0.5;
}
/* ❌ CPU-bound (slow) */
.animated {
left: 100px;
width: 300px;
}实现60fps流畅动画:
- 目标每帧耗时16ms(60fps)
- 对JS动画使用
requestAnimationFrame - 对滚动事件处理器进行防抖/节流
- 尽可能使用CSS动画
- 避免在动画期间执行长时间运行的JavaScript
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
}
});
});React/Framework Optimization
React/框架优化
React-specific:
- Use for expensive components
memo() - and
useMemo()for expensive computationsuseCallback() - 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
框架通用优化:
- 最小化重渲染
- 对高成本操作进行防抖
- 缓存计算值
- 懒加载路由和组件
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 CSS property
aspect-ratio - Reserve space for ads/embeds
- Avoid animations that cause layout shifts
css
/* Reserve space for image */
.image-container {
aspect-ratio: 16 / 9;
}- 为图片和视频设置尺寸
- 不要在现有内容上方插入新内容
- 使用 CSS属性
aspect-ratio - 为广告/嵌入内容预留空间
- 避免会导致布局偏移的动画
css
/* Reserve space for image */
.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 everywhere (creates new layers, uses memory)
will-change - 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,测试体验
- 无功能回归:确保功能仍正常工作
- 用户感知:是否感觉更快了?
记住:性能是一项功能。快速的体验会让人感觉更响应、更精致、更专业。系统化地优化,严格地测量,优先关注用户可感知的性能。