Workbox recipes
Your Service Worker script will need to import in Workbox and initialize it before calling any of the routes documented in this write-up, similar to the below:
importScripts('workbox-sw.prod.v1.3.0.js');
const workbox = new WorkboxSW();
// Placeholder array populated automatically by workboxBuild.injectManifest()
workbox.precache([]);
As a reminder, Workbox supports a number of different runtime caching strategies.
Uses a cacheFirst strategy.
workbox.router.registerRoute('https://fonts.googleapis.com/(.*)',
workbox.strategies.cacheFirst({
cacheName: 'googleapis',
cacheExpiration: {
maxEntries: 30
},
cacheableResponse: {statuses: [0, 200]}
})
);
cacheableResponse determines if something can be cached based on the response's status code. Above, the response will be cached if the response code is 0 or 200.
Uses a cacheFirst strategy.
workbox.router.registerRoute(/\.(?:png|gif|jpg|svg)$/,
workbox.strategies.cacheFirst({
cacheName: 'images-cache'
})
);
Uses a staleWhileRevalidate strategy.
workbox.router.registerRoute(/\.(?:js|css)$/,
workbox.strategies.staleWhileRevalidate({
cacheName: 'static-resources'
})
);
Uses a staleWhileRevalidate strategy. Here we're registering routes for anything from the googleapis.com and gstatic.com origins:
workbox.router.registerRoute(/.*(?:googleapis|gstatic)\.com.*$/,
workbox.strategies.staleWhileRevalidate());
I often like to keep separate cache names for each of the origins I'm caching requests for. Doing this could look like:
workbox.router.registerRoute(/.*(?:googleapis)\.com.*$/,
workbox.strategies.staleWhileRevalidate({
cacheName: 'googleapis-cache'
})
);
workbox.router.registerRoute(/.*(?:gstatic)\.com.*$/,
workbox.strategies.staleWhileRevalidate({
cacheName: 'gstatic-cache'
})
);
Uses a cacheFirst strategy.
workbox.router.registerRoute(
'https://hacker-news.firebaseio.com/v0/*',
workbox.strategies.cacheFirst({
cacheName: 'stories',
cacheExpiration: {
maxEntries: 50,
maxAgeSeconds: 300 // 5 minutes
},
cacheableResponse: {statuses: [0, 200]}
})
);
Uses a staleWhileRevalidate strategy.
For a sub-directory /static/
:
workbox.router.registerRoute(/static/(.*), workbox.strategies.staleWhileRevalidate())
As you've probably guessed, most of the path matching for setting up these routes just involves getting the regex right.
workbox.router.registerRoute('/items/:itemId',
workbox.strategies.staleWhileRevalidate({
cacheName: 'cache-with-expiration',
cacheExpiration: {
maxEntries: 20,
maxAgeSeconds: 120
}
})
);