web api instance method
Cache: put() method
Secure contextAvailable in workers
The put() method of the
Cache interface allows key/value pairs to be added to the current
Cache object.
Often, you will just want to fetch()
one or more requests, then add the result straight to your cache. In such cases you are
better off using
Cache.add()/Cache.addAll(), as
they are shorthand functions for one or more of these operations.
fetch(url).then((response) => {
if (!response.ok) {
throw new TypeError("Bad response status");
}
return cache.put(url, response);
});
[!NOTE]
put()will overwrite any key/value pair previously stored in the cache that matches the request.
[!NOTE]
add/addAlldo not cache responses withResponse.statusvalues that are not in the 200 range, whereasCache.putlets you store any request/response pair. As a result,add/addAllcan’t be used to store opaque responses, whereasCache.putcan.
Syntax
put(request, response)
Parameters
request- : The
Requestobject or URL that you want to add to the cache.
- : The
response- : The
Responseyou want to match up to the request.
- : The
Return value
A Promise that resolves with undefined.
Exceptions
TypeError- : Returned if the URL scheme is not
httporhttps.
- : Returned if the URL scheme is not
Examples
This example is from the MDN simple-service-worker example (see simple-service-worker running live).
Here we wait for a FetchEvent to fire. We construct a custom response
like so:
- Check whether a match for the request is found in the
CacheStorageusingCacheStorage.match(). If so, serve that. - If not, open the
v1cache usingopen(), put the default network request in the cache usingCache.put()and return a clone of the default network request usingreturn response.clone(). Clone is needed becauseput()consumes the response body. - If this fails (e.g., because the network is down), return a fallback response.
let response;
const cachedResponse = caches
.match(event.request)
.then((r) => (r !== undefined ? r : fetch(event.request)))
.then((r) => {
response = r;
caches.open("v1").then((cache) => cache.put(event.request, response));
return response.clone();
})
.catch(() => caches.match("/gallery/myLittleVader.jpg"));