# Performance & Optimization Reference
Comprehensive reference for web performance metrics, optimization techniques, and Core Web Vitals.
## Core Web Vitals
Google's metrics for measuring user experience.
### Largest Contentful Paint (LCP)
Measures loading performance - when largest content element becomes visible.
**Target**: < 2.5 seconds
**Optimization**:
- Reduce server response time
- Optimize images
- Remove render-blocking resources
- Use CDN
- Implement lazy loading
- Preload critical resources
```html
```
### First Input Delay (FID) → Interaction to Next Paint (INP)
FID (deprecated) measured input responsiveness. INP is the new metric.
**INP Target**: < 200ms
**Optimization**:
- Minimize JavaScript execution time
- Break up long tasks
- Use web workers
- Optimize third-party scripts
- Use `requestIdleCallback`
### Cumulative Layout Shift (CLS)
Measures visual stability - unexpected layout shifts.
**Target**: < 0.1
**Optimization**:
- Specify image/video dimensions
- Avoid inserting content above existing content
- Use CSS aspect-ratio
- Reserve space for dynamic content
```html
```
## Other Performance Metrics
### First Contentful Paint (FCP)
Time when first content element renders.
**Target**: < 1.8s
### Time to First Byte (TTFB)
Time for browser to receive first byte of response.
**Target**: < 600ms
### Time to Interactive (TTI)
When page becomes fully interactive.
**Target**: < 3.8s
### Speed Index
How quickly content is visually displayed.
**Target**: < 3.4s
### Total Blocking Time (TBT)
Sum of blocking time for all long tasks.
**Target**: < 200ms
## Image Optimization
### Format Selection
| Format | Best For | Pros | Cons |
|--------|----------|------|------|
| JPEG | Photos | Small size, widely supported | Lossy, no transparency |
| PNG | Graphics, transparency | Lossless, transparency | Larger size |
| WebP | Modern browsers | Small size, transparency | Limited old browser support |
| AVIF | Newest format | Best compression | Limited support |
| SVG | Icons, logos | Scalable, small | Not for photos |
### Responsive Images
```html
```
### Image Compression
- Use tools like ImageOptim, Squoosh, or Sharp
- Target 80-85% quality for JPEGs
- Use progressive JPEGs
- Strip metadata
## Code Optimization
### Minification
Remove whitespace, comments, shorten names:
```javascript
// Before
function calculateTotal(price, tax) {
const total = price + (price * tax);
return total;
}
// After minification
function t(p,x){return p+p*x}
```
**Tools**: Terser (JS), cssnano (CSS), html-minifier
### Code Splitting
Split code into smaller chunks loaded on demand:
```javascript
// Dynamic import
button.addEventListener('click', async () => {
const module = await import('./heavy-module.js');
module.run();
});
// React lazy loading
const HeavyComponent = React.lazy(() => import('./HeavyComponent'));
// Webpack code splitting
import(/* webpackChunkName: "lodash" */ 'lodash').then(({ default: _ }) => {
// Use lodash
});
```
### Tree Shaking
Remove unused code during bundling:
```javascript
// Only imports what's used
import { debounce } from 'lodash-es';
// ESM exports enable tree shaking
export { function1, function2 };
```
### Compression
Enable gzip or brotli compression:
```nginx
# nginx config
gzip on;
gzip_types text/plain text/css application/json application/javascript;
gzip_min_length 1000;
# brotli (better compression)
brotli on;
brotli_types text/plain text/css application/json application/javascript;
```
## Caching Strategies
### Cache-Control Headers
```http
# Immutable assets (versioned URLs)
Cache-Control: public, max-age=31536000, immutable
# HTML (always revalidate)
Cache-Control: no-cache
# API responses (short cache)
Cache-Control: private, max-age=300
# No caching
Cache-Control: no-store
```
### Service Workers
Advanced caching control:
```javascript
// Cache-first strategy
self.addEventListener('fetch', (event) => {
event.respondWith(
caches.match(event.request).then((response) => {
return response || fetch(event.request);
})
);
});
// Network-first strategy
self.addEventListener('fetch', (event) => {
event.respondWith(
fetch(event.request).catch(() => {
return caches.match(event.request);
})
);
});
// Stale-while-revalidate
self.addEventListener('fetch', (event) => {
event.respondWith(
caches.open('dynamic').then((cache) => {
return cache.match(event.request).then((response) => {
const fetchPromise = fetch(event.request).then((networkResponse) => {
cache.put(event.request, networkResponse.clone());
return networkResponse;
});
return response || fetchPromise;
});
})
);
});
```
## Loading Strategies
### Critical Rendering Path
1. Construct DOM from HTML
2. Construct CSSOM from CSS
3. Combine DOM + CSSOM into render tree
4. Calculate layout
5. Paint pixels
### Resource Hints
```html
```
### Lazy Loading
#### Images - native lazy loading
```javascript
// Intersection Observer for custom lazy loading
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
const img = entry.target;
img.src = img.dataset.src;
observer.unobserve(img);
}
});
});
document.querySelectorAll('img[data-src]').forEach(img => {
observer.observe(img);
});
```
### Critical CSS
Inline above-the-fold CSS, defer the rest:
```html