Skip to content

The Cache API Guide

The Cache API is part of the Service Worker specification, and is a great way to have more power on resources caching.

Introduction

The Cache API is part of the Service Worker specification, and is a great way to have more power on resources caching.

It allows you to cache URL-addressable resources, which means assets, web pages, HTTP APIs responses.

It’s not meant to cache individual chunks of data, which is the task of the IndexedDB API.

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 through the caches object. To detect if the API is implemented in the browser, just check for its existence using:

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

Initialize a cache

Use the caches.open API, which returns a promise with a cache object ready to be used:

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

mycache is a name that I use to identify the cache I want to initialize. It’s like a variable name, you can use any name you want.

If the cache does not exist yet, 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() returns a Response object which contains all the information about the request and the response of the network request

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

Given a cache object, its delete() method removes a cached resource from it.

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

Delete a cache

The caches.delete() method accepts a cache identifier and when executed it wipes the cache and its cached items from the system.

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

download all my books for free

  • javascript handbook
  • typescript handbook
  • css handbook
  • node.js handbook
  • astro handbook
  • html handbook
  • next.js pages router handbook
  • alpine.js handbook
  • htmx handbook
  • react handbook
  • sql handbook
  • git cheat sheet
  • laravel handbook
  • express handbook
  • swift handbook
  • go handbook
  • php handbook
  • python handbook
  • cli handbook
  • c handbook

subscribe to my newsletter to get them

Terms: by subscribing to the newsletter you agree the following terms and conditions and privacy policy. The aim of the newsletter is to keep you up to date about new tutorials, new book releases or courses organized by Flavio. If you wish to unsubscribe from the newsletter, you can click the unsubscribe link that's present at the bottom of each email, anytime. I will not communicate/spread/publish or otherwise give away your address. Your email address is the only personal information collected, and it's only collected for the primary purpose of keeping you informed through the newsletter. It's stored in a secure server based in the EU. You can contact Flavio by emailing [email protected]. These terms and conditions are governed by the laws in force in Italy and you unconditionally submit to the jurisdiction of the courts of Italy.

Related posts about platform: