Cache optimization
Caching reuses resources already downloaded: fewer requests, better LCP on repeat visits. Reference: HTTP caching - MDN.
Three cache layers
- Browser:
Cache-Control(preferred overExpires),ETag,Last-Modified. - CDN: resources served closest to the user.
- Server: Redis, Memcached, page cache (see Server).
Recommended headers
# Versioned assets (app.3f9a1c.js)
Cache-Control: public, max-age=31536000, immutable
# HTML document: always revalidate
Cache-Control: no-cacheFingerprint file names (hash) so immutable is safe.
Apache example (.htaccess)
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/webp "access plus 1 year"
ExpiresByType image/avif "access plus 1 year"
ExpiresByType font/woff2 "access plus 1 year"
ExpiresByType text/css "access plus 1 month"
ExpiresByType text/javascript "access plus 1 month"
</IfModule>Service Worker
For PWAs: cache-first, network-first or stale-while-revalidate.
self.addEventListener('fetch', e => {
e.respondWith(caches.open('v1').then(async cache => {
const hit = await cache.match(e.request);
const net = fetch(e.request).then(r => { cache.put(e.request, r.clone()); return r; });
return hit || net; // stale-while-revalidate
}));
});