Baseline Widely available
Secure context: This feature is available only in secure contexts (HTTPS), in some or all supporting browsers.
Note: This feature is available in Web 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: Cache.add
/Cache.addAll
do not cache responses with Response.status
values that are not in the 200 range, whereas Cache.put
lets you store any request/response pair. As a result, Cache.add
/Cache.addAll
can't be used to store opaque responses, whereas Cache.put
can.
request
The Request
object or URL that you want to add to the cache.
response
The Response
you want to match up to the request.
A Promise
that resolves with undefined
.
TypeError
Returned if the URL scheme is not http
or https
.
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:
CacheStorage
using CacheStorage.match()
. If so, serve that.v1
cache using open()
, put the default network request in the cache using Cache.put()
and return a clone of the default network request using return response.clone()
. Clone is needed because put()
consumes the response body.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"));
Specifications Browser compatibility See also
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.3