How to use Cache API

What is Caching?

In computing terms, a cache (pronounced cash) is hardware or software that is used to store data so that it can be quickly and temporarily accessed. Such data is either frequently accessed by a client or is likely to be accessed in the near future.

Caches are usually very small in size so that they are cost-effective and efficient. They are frequently used by cache clients such as web-browsers, the CPU, operating systems, and DNS (to name a few). Accessing data from a cache is much faster than accessing it from the main memory or any other type of storage.

The Cache API is available in all modern browsers. It can store pairs of Request and Response objects. These requests and responses contain data that is transmitted over the world wide web through http.

Creating a cache

To open a cache, use the caches.open(name) method to open any cache with a particular name:

const cache = await caches.open('new-cache');
// creating a cache

Adding anything to a cache

There are three ways to add an article to a cache:

  1. cache.add: This can be used to make a request to a network. The response is stored in the cache and cache.add() takes a single parameter, a request, or URL:
// Request
cache.add(new Request('/data.json'));

// URL 
cache.add('/data.json');
  1. cache.addAll: This methodology is similar to cache.add(). The only difference is that it takes an array or a list of requests or URLs and proceeds to add them one by one and running cache.add() for each item in the array.
const urls = ['/articleA.json', '/aricleB.json'];
cache.addAll(urls);
  1. cache.put: This method introduces a second parameter where a user can create and store their own Response. It takes two parameters. The first can either be a Request object or a URL (string). The second must be a Response, either from the network, or generated by your code:
// Response from the network
cache.put('/data.json');

// Stores in a created response
cache.put('/test.json', new Response('{"func1": "bar"}'));
Copyright ©2024 Educative, Inc. All rights reserved