Caching Strategies
Caching is the most effective way to speed up a website: the request you never have to make is the fastest request of all.
HTTP Cache Headers
# Immutable assets (JS/CSS with a hash in the filename)
Cache-Control: public, max-age=31536000, immutable
# API responses that may be stale
Cache-Control: public, max-age=60, stale-while-revalidate=300
# HTML pages: always revalidate
Cache-Control: no-cache
# Never cache at all
Cache-Control: no-store
public means a CDN may store it too. An API response that differs per user (a cart, a profile) uses private: with public, a CDN can send one person's data to another.
ETag & Last-Modified
For conditional requests, the browser asks "has this resource changed?" without downloading it again:
# The server sends
ETag: "abc123"
Last-Modified: Mon, 01 Jan 2024 00:00:00 GMT
# The browser sends on the next request
If-None-Match: "abc123"
If-Modified-Since: Mon, 01 Jan 2024 00:00:00 GMT
# The server answers 304 Not Modified (with no body)
Service Worker Cache
For finer control over the cache, and offline support:
// Cache-first strategy
self.addEventListener("fetch", (event) => {
event.respondWith(
caches.match(event.request)
.then(cached => cached || fetch(event.request))
);
});
This snippet only reads the cache and never fills it. A version that fills the cache, for assets only, is in the Service Worker Caching lesson.
Caching Strategies
- Cache-First: Static assets, fonts, images
- Network-First: API calls, dynamic content
- Stale-While-Revalidate: Show cached, update in background
TL;DR: The request you never have to make is the fastest one. Set Cache-Control by kind of resource: assets with a hash in the filename are immutable for a year, HTML is no-cache. Use ETag or Last-Modified so the browser only gets a 304, and a Service Worker for cache-first or offline support.
⚡ Cache-Control by kind of resource
Write:
Cache-Control: public, max-age=31536000, immutable
Guess first: what does this header tell the browser to do?
Keep it in the cache for 1 year without revalidating. It fits JS and CSS with a hash in the filename.
Meaning: The request you never have to make is the fastest one. HTML pages get no-cache, so they're always revalidated, and no-store means never cached at all.
⚡ Ask first, don't download again
Write:
If-None-Match: "abc123"
Meaning: Use ETag or Last-Modified, so the browser only asks whether the resource has changed. If it hasn't, the server answers 304 Not Modified with no body.
⚡ A Service Worker for finer control
Meaning: Cache-first for static assets, fonts and images. Network-first for API calls and dynamic content. Stale-while-revalidate shows what's cached while updating it in the background.