Javascript Cache API

  • 2021-06-28 10:44:11
  • OfStack

The benefit of JavaScript ServiceWorker API is that it allows WEB developers to easily control the cache.Although ETags and other technologies are also used to control the cache, using JavaScript allows programs to control the cache more powerful and free.Of course, there are powerful benefits and disadvantages to being strong -- you need to do some postprocessing, which is called cleaning up the cache.

Let's see how to create a cache object, add request cache data to the cache, delete request cache data from the cache, and finally delete the cache completely.

Determine Browser Support for Cached Object cache API

Check if the browser supports Cache API...


if('caches' in window) {
 // Has support!
}

... Check if there is an caches object in window.

Create a cache object

The way to create a cache object is to use caches.open() and pass in the name of the cache:


caches.open('test-cache').then(function(cache) {
 //  Cache creation is complete and is now accessible 
});

This caches.open method returns an Promise in which the cache object is newly created and not re-created if it was previously created.

Add Cached Data

For this type of cache, you can think of it as an array of Request objects, where key values are stored in the cache object for the response data obtained by the Request request.There are two ways to add data to a previous cache: add and addAll.Use these two methods to add the address of the request to be cached.You can refer to the article fetch API for an introduction to the Request object.

Cache requests can be added in bulk using the addAll method:


caches.open('test-cache').then(function(cache) { 
 cache.addAll(['/', '/images/logo.png'])
 .then(function() { 
 // Cached!
 });
});

This addAll method accepts an array of addresses as a parameter, and the response data for these request addresses will be cached in the cache object.addAll returns an Promise.Add a single address using the add method:


caches.open('test-cache').then(function(cache) {
 cache.add('/page/1'); // "/page/1"  The address is requested and the response data is cached. 
});

The add() method can also accept a custom Request:


caches.open('test-cache').then(function(cache) {
 cache.add(new Request('/page/1', { /*  Request parameters  */ }));
});

Similar to the add () method, the put () method can also add request addresses and its response data:


fetch('/page/1').then(function(response) {
 return caches.open('test-cache').then(function(cache) {
 return cache.put('/page/1', response);
 });
});

Accessing cached data

To view the changed request data, we can use the keys() method in the cache object to get all cached Request objects in an array:


caches.open('test-cache').then(function(cache) { 
 cache.keys().then(function(cachedRequests) { 
 console.log(cachedRequests); // [Request, Request]
 });
});

/*
Request {
 bodyUsed: false
 credentials: "omit"
 headers: Headers
 integrity: ""
 method: "GET"
 mode: "no-cors"
 redirect: "follow"
 referrer: ""
 url: "http://www.webhek.com/images/logo.png"
}
*/

If you want to view the response content of a cached Request request, you can use the cache.match() or cache.matchAll() methods:


caches.open('test-cache').then(function(cache) {
 cache.match('/page/1').then(function(matchedResponse) {
 console.log(matchedResponse);
 });
});

/*
Response {
 body: (...),
 bodyUsed: false,
 headers: Headers,
 ok: true,
 status: 200,
 statusText: "OK",
 type: "basic",
 url: "https://www.webhek.com/page/1"
}
*/

You can refer to the article fetch API for usage and details of the Response object.

Delete data from cache

To delete data from the cache, we can use the delete() method in the cache object:


caches.open('test-cache').then(function(cache) {
 cache.delete('/page/1');
});

In this way, there will no longer be/page/1 request data in the cache.

Get the name of the cache in the existing cache

To get the name of the cache data that already exists in the cache, we need to use the caches.keys() method:


caches.keys().then(function(cacheKeys) { 
 console.log(cacheKeys); // ex: ["test-cache"]
});

window.caches.keys() also returns an Promise.

Delete a cached object

To delete a cached object, you only need the key name of the cache:


caches.open('test-cache').then(function(cache) {
 //  Cache creation is complete and is now accessible 
});
0

Large number of ways to delete old cached data:


caches.open('test-cache').then(function(cache) {
 //  Cache creation is complete and is now accessible 
});
1

Want to be an service worker expert?These codes above are worth putting in your repository.Both Firefox Browser and Google Browser support service worker, and we believe that more websites and app will soon use this caching technology to speed up their operations.


Related articles: