workbox-sw. WorkboxSW
This class uses the Workbox libraries to create a clean and easy API for common caching and serving needs.
Constructor
WorkboxSW
new WorkboxSW(input)
You should instantiate this class with new self.WorkboxSW()
.
Parameter |
|||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
input |
Object Values in
|
Properties
router
Router
The router for this library is exposed via the router
parameter. This is an instance of the Router.
Example
const workboxSW = new WorkboxSW();
workboxSW.router.registerRoute('/', workboxSW.workbox.cacheFirst());
runtimeCacheName
The name of the cache used by default by the runtime caching strategies.
Entries that are managed via precache()
are stored in a separate cache with a different name.
You can override the default cache name when constructing a strategy if you'd prefer, via
workboxSW.strategies.cacheFirst({cacheName: 'my-cache-name'});
If you would like to explicitly add to, remove, or check the contents of the default cache, you can use the Cache Storage API to pass in the default cache name to
caches.open()
. This can be useful if you want to "prime" your cache with remote resources that can't be properly managed via precache()
.
Example
const cache = await caches.open(workboxSW.runtimeCacheName);
await cache.add('https://third-party.com/path/to/file');
const contentsOfRuntimeCache = await cache.keys();
strategies
The supported caching strategies shipped with workbox-sw are provided via the strategies
object.
See Strategies for a complete list.
Example
const workboxSW = new WorkboxSW();
workboxSW.router.registerRoute('/styles/*',
workboxSW.strategies.cacheFirst());
Method
precache
precache(revisionedFiles)
Revisioned assets can be cached intelligently during the install (i.e. old files are cleared from the cache, new files are added to the cache and unchanged files are left as is).
The input needs to be an array of URL strings which having revisioning details in them otherwise the entry should be an object with url
and
revision
parameters.
In addition to maintaining the cache, this method will also set up the necessary routes to serve the precached assets using a cache-first strategy.
Parameter |
|
---|---|
revisionedFiles |
Array of (String or Object) A set of urls to cache when the service worker is installed. |
Example
Cache revisioned assets.
// Cache a set of revisioned URLs
const workboxSW = new WorkboxSW();
workboxSW.precache([
'/styles/main.613e6c7332dd83e848a8b00c403827ed.css',
'/images/logo.59a325f32baad11bd47a8c515ec44ae5.jpg'
]);
// ...precache() can also take objects to cache
// non-revisioned URLs.
// Please use workbox-build or the workbox CLI to generate the manifest for
// you.
workboxSW.precache([
{
url: '/index.html',
revision: '613e6c7332dd83e848a8b00c403827ed'
},
{
url: '/about.html',
revision: '59a325f32baad11bd47a8c515ec44ae5'
}
]);