1---
2name: optimize
3description: Diagnoses and fixes UI performance across loading speed, rendering, animations, images, and bundle size. Use when the user mentions slow, laggy, janky, performance, bundle size, load time, or wants a faster, smoother experience.
4version: 2.1.1
5user-invocable: true
6argument-hint: "[target]"
7---
8
9Identify and fix performance issues to create faster, smoother user experiences.
10
11## Assess Performance Issues
12
13Understand current performance and identify problems:
14
151. **Measure current state**:
16 - **Core Web Vitals**: LCP, FID/INP, CLS scores
17 - **Load time**: Time to interactive, first contentful paint
18 - **Bundle size**: JavaScript, CSS, image sizes
19 - **Runtime performance**: Frame rate, memory usage, CPU usage
20 - **Network**: Request count, payload sizes, waterfall
21
222. **Identify bottlenecks**:
23 - What's slow? (Initial load? Interactions? Animations?)
24 - What's causing it? (Large images? Expensive JavaScript? Layout thrashing?)
25 - How bad is it? (Perceivable? Annoying? Blocking?)
26 - Who's affected? (All users? Mobile only? Slow connections?)
27
28**CRITICAL**: Measure before and after. Premature optimization wastes time. Optimize what actually matters.
29
30## Optimization Strategy
31
32Create systematic improvement plan:
33
34### Loading Performance
35
36**Optimize Images**:
37- Use modern formats (WebP, AVIF)
38- Proper sizing (don't load 3000px image for 300px display)
39- Lazy loading for below-fold images
40- Responsive images (`srcset`, `picture` element)
41- Compress images (80-85% quality is usually imperceptible)
42- Use CDN for faster delivery
43
44```html
45<img
46 src="hero.webp"
47 srcset="hero-400.webp 400w, hero-800.webp 800w, hero-1200.webp 1200w"
48 sizes="(max-width: 400px) 400px, (max-width: 800px) 800px, 1200px"
49 loading="lazy"
50 alt="Hero image"
51/>
52```
53
54**Reduce JavaScript Bundle**:
55- Code splitting (route-based, component-based)
56- Tree shaking (remove unused code)
57- Remove unused dependencies
58- Lazy load non-critical code
59- Use dynamic imports for large components
60
61```javascript
62// Lazy load heavy component
63const HeavyChart = lazy(() => import('./HeavyChart'));
64```
65
66**Optimize CSS**:
67- Remove unused CSS
68- Critical CSS inline, rest async
69- Minimize CSS files
70- Use CSS containment for independent regions
71
72**Optimize Fonts**:
73- Use `font-display: swap` or `optional`
74- Subset fonts (only characters you need)
75- Preload critical fonts
76- Use system fonts when appropriate
77- Limit font weights loaded
78
79```css
80@font-face {
81 font-family: 'CustomFont';
82 src: url('/fonts/custom.woff2') format('woff2');
83 font-display: swap; /* Show fallback immediately */
84 unicode-range: U+0020-007F; /* Basic Latin only */
85}
86```
87
88**Optimize Loading Strategy**:
89- Critical resources first (async/defer non-critical)
90- Preload critical assets
91- Prefetch likely next pages
92- Service worker for offline/caching
93- HTTP/2 or HTTP/3 for multiplexing
94
95### Rendering Performance
96
97**Avoid Layout Thrashing**:
98```javascript
99// ❌ Bad: Alternating reads and writes (causes reflows)
100elements.forEach(el => {
101 const height = el.offsetHeight; // Read (forces layout)
102 el.style.height = height * 2; // Write
103});
104
105// ✅ Good: Batch reads, then batch writes
106const heights = elements.map(el => el.offsetHeight); // All reads
107elements.forEach((el, i) => {
108 el.style.height = heights[i] * 2; // All writes
109});
110```
111
112**Optimize Rendering**:
113- Use CSS `contain` property for independent regions
114- Minimize DOM depth (flatter is faster)
115- Reduce DOM size (fewer elements)
116- Use `content-visibility: auto` for long lists
117- Virtual scrolling for very long lists (react-window, react-virtualized)
118
119**Reduce Paint & Composite**:
120- Use `transform` and `opacity` for animations (GPU-accelerated)
121- Avoid animating layout properties (width, height, top, left)
122- Use `will-change` sparingly for known expensive operations
123- Minimize paint areas (smaller is faster)
124
125### Animation Performance
126
127**GPU Acceleration**:
128```css
129/* ✅ GPU-accelerated (fast) */
130.animated {
131 transform: translateX(100px);
132 opacity: 0.5;
133}
134
135/* ❌ CPU-bound (slow) */
136.animated {
137 left: 100px;
138 width: 300px;
139}
140```
141
142**Smooth 60fps**:
143- Target 16ms per frame (60fps)
144- Use `requestAnimationFrame` for JS animations
145- Debounce/throttle scroll handlers
146- Use CSS animations when possible
147- Avoid long-running JavaScript during animations
148
149**Intersection Observer**:
150```javascript
151// Efficiently detect when elements enter viewport
152const observer = new IntersectionObserver((entries) => {
153 entries.forEach(entry => {
154 if (entry.isIntersecting) {
155 // Element is visible, lazy load or animate
156 }
157 });
158});
159```
160
161### React/Framework Optimization
162
163**React-specific**:
164- Use `memo()` for expensive components
165- `useMemo()` and `useCallback()` for expensive computations
166- Virtualize long lists
167- Code split routes
168- Avoid inline function creation in render
169- Use React DevTools Profiler
170
171**Framework-agnostic**:
172- Minimize re-renders
173- Debounce expensive operations
174- Memoize computed values
175- Lazy load routes and components
176
177### Network Optimization
178
179**Reduce Requests**:
180- Combine small files
181- Use SVG sprites for icons
182- Inline small critical assets
183- Remove unused third-party scripts
184
185**Optimize APIs**:
186- Use pagination (don't load everything)
187- GraphQL to request only needed fields
188- Response compression (gzip, brotli)
189- HTTP caching headers
190- CDN for static assets
191
192**Optimize for Slow Connections**:
193- Adaptive loading based on connection (navigator.connection)
194- Optimistic UI updates
195- Request prioritization
196- Progressive enhancement
197
198## Core Web Vitals Optimization
199
200### Largest Contentful Paint (LCP < 2.5s)
201- Optimize hero images
202- Inline critical CSS
203- Preload key resources
204- Use CDN
205- Server-side rendering
206
207### First Input Delay (FID < 100ms) / INP (< 200ms)
208- Break up long tasks
209- Defer non-critical JavaScript
210- Use web workers for heavy computation
211- Reduce JavaScript execution time
212
213### Cumulative Layout Shift (CLS < 0.1)
214- Set dimensions on images and videos
215- Don't inject content above existing content
216- Use `aspect-ratio` CSS property
217- Reserve space for ads/embeds
218- Avoid animations that cause layout shifts
219
220```css
221/* Reserve space for image */
222.image-container {
223 aspect-ratio: 16 / 9;
224}
225```
226
227## Performance Monitoring
228
229**Tools to use**:
230- Chrome DevTools (Lighthouse, Performance panel)
231- WebPageTest
232- Core Web Vitals (Chrome UX Report)
233- Bundle analyzers (webpack-bundle-analyzer)
234- Performance monitoring (Sentry, DataDog, New Relic)
235
236**Key metrics**:
237- LCP, FID/INP, CLS (Core Web Vitals)
238- Time to Interactive (TTI)
239- First Contentful Paint (FCP)
240- Total Blocking Time (TBT)
241- Bundle size
242- Request count
243
244**IMPORTANT**: Measure on real devices with real network conditions. Desktop Chrome with fast connection isn't representative.
245
246**NEVER**:
247- Optimize without measuring (premature optimization)
248- Sacrifice accessibility for performance
249- Break functionality while optimizing
250- Use `will-change` everywhere (creates new layers, uses memory)
251- Lazy load above-fold content
252- Optimize micro-optimizations while ignoring major issues (optimize the biggest bottleneck first)
253- Forget about mobile performance (often slower devices, slower connections)
254
255## Verify Improvements
256
257Test that optimizations worked:
258
259- **Before/after metrics**: Compare Lighthouse scores
260- **Real user monitoring**: Track improvements for real users
261- **Different devices**: Test on low-end Android, not just flagship iPhone
262- **Slow connections**: Throttle to 3G, test experience
263- **No regressions**: Ensure functionality still works
264- **User perception**: Does it *feel* faster?
265
266Remember: Performance is a feature. Fast experiences feel more responsive, more polished, more professional. Optimize systematically, measure ruthlessly, and prioritize user-perceived performance.