Cache API
If we want to be able to load the entire app without using the network,
we need a place to store the resources (i.e. HTML, CSS, JavaScript, images, fonts, etc.).
This place is the Cache API.
A cache box contains request and response pairs, from any secure origin. We can use it to store any thing really.
The Cache API gives us this caches object on the global.
Create Cache / Open Created Cache
caches.open('my-stuff').then(function(cache) {
//...
});
That returns a promise for a cache with that name (i.e. my-stuff
).
Add Items
To add assets to cache, use cache.put()
cache.put(request, response);
Or use cache.addAll()
cache.addAll([
'/foo',
'/bar'
]);
This operation is atomic; if any of them fail to cache, none of them are added.
addAll()
uses fetch()
under the hood, so bear in mind that requests will go via the browser cache.
Get Items
You can get item(s) out of the cache using cache.match()
cache.match(request);
// Or //
caches.match(request);
The method caches.match()
does the same thing, but it tries to find a match in any stored cache.
All of the methods above can take a request or a url.