SKILL.md

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