Service Worker Cache for Placeholder Image URLs
Use a service worker image cache to intercept placeholder URL requests, serve fallbacks offline, and control cache lifetime for deterministic placeholder images.
A service worker sitting between your app and the network can intercept every image request and return a cached copy when the network is unavailable or slow. Registering a service worker image cache for placeholder URLs means branded fallback images load instantly even offline, without a second network round trip.
This guide covers Workbox routing strategies for image caches, manual Cache API usage for specific fallback URLs, cache expiration policies, and how to serve fallback.pics responses as offline fallbacks.
Architecture
Where a service worker fits in the image loading pipeline
The browser fetches images through the network stack. A service worker intercepts fetch events before they reach the network. You can inspect the request URL, decide whether to return a cached response, forward to the network, or respond with a synthetic image — all without touching application code.
For placeholder.pics URLs this is particularly useful: the first fetch goes to the CDN, the response is cached locally, and every subsequent request for the same URL returns instantly from the Cache API. For a product grid with 50 identical card placeholders, this eliminates 49 network requests.
Workbox
Routing placeholder image requests with Workbox strategies
Workbox's StaleWhileRevalidate strategy serves placeholder images from cache immediately while updating the cache in the background. This is the right strategy for placeholder images where a slightly stale response is acceptable and speed matters more than freshness.
CacheFirst works for immutable placeholder URLs. Fallback.pics URLs return Cache-Control: public, max-age=31536000, immutable, which aligns with CacheFirst. Once cached, the image is served from disk without a network request for an entire year.
// service-worker.js (Workbox)
import { registerRoute } from 'workbox-routing';
import { CacheFirst, StaleWhileRevalidate } from 'workbox-strategies';
import { ExpirationPlugin } from 'workbox-expiration';
// Fallback.pics placeholder images — immutable, cache forever
registerRoute(
({ url }) => url.hostname === 'fallback.pics',
new CacheFirst({
cacheName: 'placeholder-images-v1',
plugins: [
new ExpirationPlugin({
maxEntries: 200,
maxAgeSeconds: 60 * 60 * 24 * 365, // 1 year
}),
],
})
);
// Your own image CDN — stale-while-revalidate
registerRoute(
({ url }) => url.hostname === 'cdn.yourapp.com',
new StaleWhileRevalidate({
cacheName: 'app-images-v1',
plugins: [
new ExpirationPlugin({
maxEntries: 500,
maxAgeSeconds: 60 * 60 * 24 * 30, // 30 days
}),
],
})
); Manual Cache API
Pre-caching specific fallback URLs at service worker install
If you know which fallback URLs your app uses — typically a small set of dimension-matched placeholders — pre-cache them during the service worker install event. The install step blocks activation until all URLs are cached, guaranteeing offline availability from the first page load.
Pre-cache only the URLs that are used before the user interacts with the app. Caching 50 placeholder dimensions on install adds latency to the service worker lifecycle.
// service-worker.js — manual pre-cache
const PLACEHOLDER_CACHE = 'placeholder-images-v1';
const FALLBACK_URLS = [
'https://fallback.pics/api/v1/400x300/7C3AED/FFFFFF?text=No+Image',
'https://fallback.pics/api/v1/avatar/80?text=AB',
'https://fallback.pics/api/v1/200x200/7C3AED/FFFFFF?text=Product',
];
self.addEventListener('install', (event) => {
event.waitUntil(
caches.open(PLACEHOLDER_CACHE).then((cache) =>
cache.addAll(FALLBACK_URLS)
)
);
self.skipWaiting();
});
// Offline fallback: if image fetch fails, return a cached placeholder
self.addEventListener('fetch', (event) => {
if (event.request.destination === 'image') {
event.respondWith(
fetch(event.request).catch(() =>
caches.match('https://fallback.pics/api/v1/400x300/7C3AED/FFFFFF?text=Offline')
)
);
}
}); Cache versioning
Cache invalidation and version management
Service worker caches persist across page loads and browser restarts. Rename the cache (e.g. placeholder-images-v2) in the activate event to clear stale entries when you update your placeholder URLs. Delete old cache versions during activation to prevent unbounded disk growth.
Workbox handles versioning automatically when you use the GenerateSW plugin with a revision hash. Manual Cache API usage requires explicit version management in the activate event.
const CURRENT_CACHES = ['placeholder-images-v2', 'app-images-v1'];
self.addEventListener('activate', (event) => {
event.waitUntil(
caches.keys().then((cacheNames) =>
Promise.all(
cacheNames
.filter((name) => !CURRENT_CACHES.includes(name))
.map((name) => caches.delete(name))
)
)
);
self.clients.claim();
}); Performance
Measuring cache hit rate for placeholder images
Use the Performance Timeline API to measure image load times before and after the service worker is active. Cache hits from the Cache API should resolve in under 10ms; network hits take 50–200ms for fallback.pics edge responses.
Log cache misses to a beacon endpoint during development to identify which placeholder URLs are not pre-cached. A cache miss on every page load for a commonly used avatar placeholder indicates it should be added to the pre-cache list.
Key takeaways
What to standardize before shipping
- A service worker intercepts image fetch events before they reach the network, enabling instant offline delivery of cached placeholder images.
- Use CacheFirst for fallback.pics URLs since they return immutable Cache-Control headers; once cached they never need re-fetching.
- Pre-cache a small set of commonly used fallback URLs during the service worker install event to guarantee offline availability from first load.
- Rename cache versions in the activate event and delete stale caches to prevent unbounded disk growth as placeholder URLs change.
- Measure cache hit latency with the Performance Timeline API to verify that placeholder images are loading from the cache rather than the network.
Production fallback layer
Use fallback.pics anywhere an image URL is accepted.
Start with one deterministic URL and standardize fallback behavior across your design system.