Image Format Selection: JPEG vs WebP vs AVIF and Client Negotiation
Format Efficiency Comparison
Image formats vary dramatically in compression efficiency. JPEG (1992) achieves roughly 10:1 compression. Universal support but dated algorithms. Best for photos, poor for graphics with sharp edges. WebP (2010) is 25-35% smaller than JPEG at equivalent quality. Supports transparency. Supported by 97% of browsers. AVIF (2020) is 50% smaller than JPEG. Excellent quality at low bitrates. Supports HDR. Supported by 90% of browsers but encoding is CPU intensive (10x slower than WebP).
Content Type Considerations
Format choice depends on image content. Photos: AVIF or WebP for modern browsers, JPEG fallback. Lossy compression acceptable. Graphics with text or sharp edges: PNG or WebP lossless. JPEG artifacts visible on sharp edges. Transparency required: PNG (universal), WebP (modern), or AVIF. Animation: WebP animated or AVIF sequences over GIF. GIF is limited to 256 colors and massive file sizes. A 5MB GIF becomes 500KB WebP animated.
Content Negotiation with Accept Header
Browsers send Accept header listing supported formats. Chrome sends image/avif,image/webp,image/*. Safari historically sent only image/* (now supports WebP). Server reads Accept header, serves best supported format, sets Vary: Accept header to ensure correct caching. Without Vary header, CDN might cache WebP and serve it to clients that do not support WebP. Critical: CDN must support Vary header caching or use separate cache keys per format.
Picture Element and Srcset
HTML provides client side format selection. The <picture> element lists sources in preference order. Browser picks first supported format. The srcset attribute enables resolution switching. srcset="small.jpg 400w, large.jpg 1200w" tells browser image widths. Browser selects based on viewport and pixel density. Combine picture and srcset: multiple formats at multiple resolutions. Six source declarations cover AVIF, WebP, JPEG at 2x and 1x resolutions.
Client Hints for Smarter Decisions
Client hints provide additional context. DPR (device pixel ratio) indicates retina displays. Viewport-Width gives layout viewport size. Save-Data indicates user prefers reduced data. Downlink provides estimated bandwidth. Server uses hints to select optimal variant: user with Save-Data: on gets lower quality. User with DPR: 3 gets high resolution. Edge CDNs can process hints without origin involvement.
Fallback Strategy
Always have fallback chain. Optimal: AVIF for 90% of modern browsers. Fallback: WebP for additional 7%. Ultimate fallback: JPEG for remaining 3%. Over time, AVIF support grows and fallback traffic decreases. Monitor format distribution: when fallback traffic drops below 1%, consider dropping JPEG generation to save storage. But enterprise environments with locked browsers may need JPEG longer than consumer web.