Web Cache

The Web Cache API stores request-response pairs of fetch results to ease repeated loading of resources, using the global object -- caches.

The Cache storage persists across sessions like localStorage, ie. still exists even after the browser has been closed. It can store a large amount of data (up to gigabytes) and it cannot be accessed across domains.

Chrome and Safari only expose `CacheStorage` to the windowed context over HTTPS. window.caches will be undefined unless an SSL certificate is configured.

Below, we attempt to rewrite the fetch() function so that it retrieves a resource from the cache storage (stored locally on the client's device) if it has already been retrieved before.
<!doctype html><html>
<body><script>
   var myCacheName = "cache A";
   async function myFetch(url){
      const myCache = await caches.open(myCacheName);
       var response = await myCache.match(url);
       if (response) return await response.json();
       await myCache.add(url);     // fetches the resource
       response = await myCache.match(url);
       return await response.json();
    }
    (async()=>{
       console.log(await myFetch("cache_test.json"));
    })();
</script></body></html>

A request can be supplied in the form of a Request object, and an array of URLs can be added or matched to the cache at the same time:

myCache.addAll(['/weather/today.json', new Request('/data.json')]);caches.open('v1').then(function(cache) { cache.matchAll('/images/').then(function(response) { response.forEach(function(element, index, array) { cache.delete(element); }); }); });

The put() method is more permissive than either add() or addAll(), and will allow you to store non-CORS responses or other responses where the status code of the response is not in the 200 range. It will overwrite any previous responses for the same request.

// Retreive data.json from the server and store the response.myCache.put('/data.json'); // Create a new entry for test.json and store the newly created response.myCache.put('/test.json', new Response('{"foo": "bar"}'));

Two requests are considered different if they have different query strings, 'Vary' headers, or HTTP methods (GET, POST, PUT, etc.). However, you can set your own criteria:

const options = { ignoreSearch: true, ignoreMethod: true, ignoreVary: true}; const response = await myCache.match(request, options);

To delete a cache entry:

myCache.delete(request); myCache.delete('/example/file.txt', {ignoreVary: true, ignoreSearch: true});

To obtain the array of cache keys:

const k = await cache.keys(); // cache.keys(request, {options}).then(function(keys) { /* do something with your array of requests */ });

The cache storage for a site persists even after the browser has been closed.