JavaScript Cache API

The awesome ServiceWorker API is meant to give developers a bit more control over what is and isn't cached, and how. Sure we can play games with ETags and the like but doing it programmatically with JavaScript just feels better, more controllable. As with every API, however, adding stuff to cache isn't just fun and games -- you have to do the cleanup work yourself too, and by "cleanup work" I mean having to delete cache.

Let's have a look at how you can get caches, add and delete requests from caches, and how you can then delete an entire cache!

Detecting the cache API

To detect if the browser supports the Cache API...

if('caches' in window) {
  // Has support!
}

...check for the presence of the caches object within the window.

Creating a Cache

Creating a cache requires a caches.open call with a cache name:

caches.open('test-cache').then(function(cache) {
  // Cache is created and accessible
});

The caches.open call returns a Promise and the cache object that was either created or existed before the open call.

Adding to Cache

You can think of a cache as an array of Request objects which act as keys to their responses which are stored by the browser. Simple addition to cache is happens via two main methods: add and addAll. You can provide these methods a string for the URL that should be fetched and cached or a Request object. You can learn more about Request objects by reading my fetch API post.

To batch add URLs to cache, you can use the addAll method:

caches.open('test-cache').then(function(cache) { 
  cache.addAll(['/', '/images/logo.png'])
    .then(function() { 
      // Cached!
    });
});

The addAll method accepts an array of URLs whose URLs and responses should be cached. addAll returns a Promise. To add a single URL, use the add method:

caches.open('test-cache').then(function(cache) {
  cache.add('/page/1');  // "/page/1" URL will be fetched and cached!
});

add can also accept a custom Request:

caches.open('test-cache').then(function(cache) {
  cache.add(new Request('/page/1'));
});

Similar to add is put whereby you can add a URL and its Response object:

fetch('/page/1').then(function(response) {
  return caches.open('test-cache').then(function(cache) {
    return cache.put('/page/1', response);
  });
});

Read more @ David Walsh Blog