AI Workshop: learn to build apps with AI →
PWA & Service Workers: Cache API

Join the AI Workshop and learn to build real-world apps with AI. A hands-on, practical program to level up your skills.


Introduction

The Cache API is part of the Service Worker specification and gives you control over caching URL-addressable resources.

Use it to cache assets, pages, and HTTP API responses. It is not for arbitrary data; use the IndexedDB API for that.

It’s currently available in Chrome >= 40, Firefox >=39 and Opera >= 27.

Safari and Edge recently introduced support for it.

Internet Explorer does not support it.

Mobile support is good on Android, supported on the Android Webview and in Chrome for Android, while on iOS it’s only available to Opera Mobile and Firefox Mobile users.

Detect if the Cache API is available

The Cache API is exposed as caches. To check if it is available:

if ('caches' in window) {
  //ok
}

Initialize a cache

Use caches.open(name), which returns a promise that resolves to a cache object:

caches.open('mycache').then((cache) => {
  // you can start using the cache
})

Use any string as the cache name. If the cache does not exist, caches.open() creates it.

Add items to the cache

The cache object exposes two methods to add items to the cache: add and addAll.

cache.add()

add accepts a single URL, and when called it fetches the resource and caches it.

caches.open('mycache').then((cache) => {
  cache.add('/api/todos')
})

To allow more control on the fetch, instead of a string you can pass a Request object, part of the Fetch API specification:

caches.open('mycache').then((cache) => {
  const options = {
    // the options
  }
  cache.add(new Request('/api/todos', options))
})

cache.addAll()

addAll accepts an array, and returns a promise when all the resources have been cached.

caches.open('mycache').then((cache) => {
  cache.addAll(['/api/todos', '/api/todos/today']).then(() => {
    // all requests were cached
  })
})

Manually fetch and add

cache.add() automatically fetches a resource, and caches it.

The Cache API offers a more granular control on this via cache.put(). You are responsible for fetching the resource and then telling the Cache API to store a response:

const url = '/api/todos'
fetch(url).then((res) => {
  return caches.open('mycache').then((cache) => {
    return cache.put(url, res)
  })
})

Retrieve an item from the cache

cache.match(request) returns a Response object for the cached request, or undefined if not found

caches.open('mycache').then((cache) => {
  cache.match('/api/todos').then((res) => {
    //res is the Response Object
  })
})

Get all the items in a cache

caches.open('mycache').then((cache) => {
  cache.keys().then((cachedItems) => {
    //
  })
})

cachedItems is an array of Request objects, which contain the URL of the resource in the url property.

Get all the available caches

The caches.keys() method lists the keys of every cache available.

caches.keys().then((keys) => {
  // keys is an array with the list of keys
})

Remove an item from the cache

Use cache.delete(request) to remove a cached resource.

caches.open('mycache').then((cache) => {
  cache.delete('/api/todos')
})

Delete a cache

caches.delete(cacheName) removes the cache and all its entries.

caches.delete('mycache').then(() => {
  // deleted successfully
})

Lessons in this unit:

0: Introduction
1: Progressive Web Apps
2: Service Workers
3: ▶︎ Cache API
4: Making a website work offline
5: Notifications API
6: Push API
7: Unregister service workers in Safari