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