Learn how to Cache resources using the Cache API in JavaScript.

The Cache API allows service workers to control the resources to be cached (HTML pages, CSS, JavaScript files, images, JSON, and so on). Through the Cache API, service workers can Cache resources for offline use and retrieve them later.

Checking Cache support

Check that the Caches object is available in the window.

let isCacheSupported = 'caches' in window;
Copy the code

Caches are an example of CacheStorage.

Create or initialize the Cache

We can use the open method to create a cache with a name, which returns a promise. If the cache already exists, no new cache is created.

caches.open('cacheName').then( cache= >{});Copy the code
  • You cannot access caches set up for other sources (domains).
  • The cache you are creating will be created for your domain.
  • You can add multiple caches for the same domain, which can be passedcaches.keys()Access.

Add the item to the cache

There are three methods to cache resources: add, addAll, and set. The add() and addAll() methods automatically get the resource and cache it, while in the set method we get the data and set the cache.

add

let cacheName = 'userSettings'; 
let url = '/api/get/usersettings';
caches.open(cacheName).then( cache= > {
   cache.add(url).then( () = > {
       console.log("Data cached ")}); });Copy the code

In the code above, the internal request for the/API /get/ UserSettings URL is sent to the server, and the response is cached once the data is received.

addAll

AddAll takes an array of urls and returns a Promise when all resources are cached.

let urls = ['/get/userSettings? userId=1'.'/get/userDetails'];
caches.open(cacheName).then( cache= > {
cache.addAll(urls).then( () = > {
       console.log("Data cached ")}); });Copy the code

Cache.add/ cache.addall does not Cache responses whose response. status is not in the 200 range. Cache.put lets you store any request/Response pairs.

put

Put adds a key/value pair to the current Cache object. In PUT, we need to manually fetch the request and set the value.

Note: Put () overwrites any key/value pairs previously stored in the cache that match the request.

let cacheName = 'userSettings';
let url = '/api/get/userSettings';
fetch(url).then(res= > {
  return caches.open(cacheName).then(cache= > {
    returncache.put(url, res); })})Copy the code

Retrieve from the cache

Use cache.match() to get the Response stored to the URL.

const cacheName = 'userSettings'
const url = '/api/get/userSettings'
caches.open(cacheName).then(cache= > {
  cache.match(url).then(settings= > {
    console.log(settings); }});Copy the code

Settings is a response object that looks like

Response {
  body: (...). .bodyUsed: false.headers: Headers,
  ok: true.status: 200.statusText: "OK".type: "basic".url: "https://test.com/api/get/userSettings"
}
Copy the code

Retrieves all items in the cache

The cache object contains the keys methods, which will have all the urls of the currently cached object.

caches.open(cacheName).then( (cache) = > { 
  cache.keys().then((arrayOfRequest) = > { 
      console.log(arrayOfRequest); // [Request, Request]
  });
});
Copy the code

An arrayOfRequest is an arrayOfRequest objects that contains all the details about the Request.

Retrieve all caches

caches.keys().then(keys= > {
  // keys is an array containing a list of keys
})
Copy the code

Removes items from the cache

You can use the delete method on a cache object to delete a specific cache request.

let cacheName = userSettings; 
let urlToDelete = '/api/get/userSettings';
caches.open(cacheName).then(cache= > {
  cache.delete(urlToDelete)
})
Copy the code

Remove cache completely

caches.delete(cacheName).then(() = > {
   console.log('Cache successfully deleted! ');
})
Copy the code

Source: public account: Front-end Full Stack Developer (ID: BY-Zhangbing-dev)