Tutorial

First Steps with the Cache API

Published on August 20, 2018
Default avatar

By Flavio Copes

First Steps with the Cache API

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

The Cache API was created to allow Service Workers to have a deeper and fine-grained control over the caching of resources.

Through the Cache API a Service Worker can decide to cache resources for offline consumption and retrieve them later.

With resources, we mean complete responses from URL, like HTML pages, CSS, JavaScript files, images, JSON, and any other resource that can be consumed by your web pages or web apps.

Browser Support

You can’t talk about recent web technology without detailing which are the browsers supported.

In the case of the Cache API, we are talking about:

  • Firefox 39 and higher
  • Chrome 40 and higher
  • Opera 29 and higher
  • Safari 11.1 and higher
  • iOS Safari 11.4 and higher
  • Edge 17 and higher
  • UC Browser 11.8 and higher
  • Chrome for Android 67 and higher

There is no support for Internet Explorer.

Other than Firefox and Chrome, support in other browsers has been introduced really recently, so you should keep this in mind.

Your sites and applications, if you plan to support more than just people that run the browsers above mentioned, should have any Cache API code inside this check:

if ('caches' in window) {
  // The Cache API is supported

  // You can add your code here
}

Working with caches

if ('caches' in window) {
  // The Cache API is supported
  const cacheName = 'my-website-cache'
  caches.open(cacheName).then(cache => {
    // you can start using the cache
  })
}

A cache is linked to the current origin (domain), and for security and privacy reasons you cannot access caches set up for others.

You can set up several different caches. To see all the caches set up for the current origin, you can iterate over caches.keys():

caches.keys().then(keys => {
  keys.map(key => {
    console.log(key)
  })
})

You can delete one cache by calling the delete() method:

const cacheName = 'my-website-cache'
caches.delete(cacheName).then(() => {
  console.log('Cache deleted')
})

Adding to a cache

We have 3 methods:

  • cache.put()
  • cache.add()
  • cache.addAll()

You call cache.put() in the successful promise callback of a fetch() call:

const cacheName = 'my-website-cache'
const url = '/resource'
fetch(url).then(res => {
  return caches.open(cacheName).then(cache => {
    return cache.put(url, res)
  })
})

With cache.add() you don’t manually have to fetch the resource prior to adding it to the cache: the Cache API makes this automatically for you.

const cacheName = 'my-website-cache'
const url = '/resource'
caches.open(cacheName).then(cache => {
  cache.add(url).then(() => {
    //done!
  }
})

In this case, following the cache.add() call, a Fetch request is sent to the server, and the response is cached.

cache.addAll() is used to perform requests to multiple URLs. The callback function is only called when all the resources have been fetched and cached:

const cacheName = 'my-website-cache'
const url1 = '/resource1'
const url2 = '/resource2'
caches.open(cacheName).then(cache => {
  cache.addAll([url1, url2]).then(() => {
    //all requests were cached
  })
})

Retrieving from a cache

Using cache.match() you can get the Response object that was stored corresponding to the URL that matches your query:

const cacheName = 'my-website-cache'
const url = '/resource'
caches.open(cacheName).then(cache => {
  cache.match(url).then(item => {
    console.log(item)
  }
})

item is a Request object which you can inspect, for example, you can get the URL using item.url.

Iterate Over All Items in the Cache

Using cache.keys() you can get all the items that are present in a cache, and iterate over them:

const cacheName = 'my-website-cache'
const url = '/resource'
caches.open(cacheName).then(cache => {
  cache.keys().then(items => {
    items.map(item => {
      console.log(item)
    })
  }
})

Each item is a Request object.

Removing an item from the cache

Once a resource is added to the cache, it takes up some amount of space in the browser’s storage. You can manually clear anything you stored by its original URL, passing it to the cache.delete() method:

const cacheName = 'my-website-cache'
const url = '/resource'
caches.open(cacheName).then(cache => {
  cache.delete(url).then(() => {
    //deleted successfully!
  }
})

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about us


About the authors
Default avatar
Flavio Copes

author

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
Leave a comment


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Get our biweekly newsletter

Sign up for Infrastructure as a Newsletter.

Hollie's Hub for Good

Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

Become a contributor

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

Welcome to the developer cloud

DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

Learn more
DigitalOcean Cloud Control Panel