Javascript Get Cache and Clear Cache API (reload)

Keywords: Javascript Firefox Google

From: http://geek.csdn.net/news/detail/199421

The benefit of the JavaScript ServiceWorker API is that it allows web developers to easily control the cache.Although technologies such as ETags 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 post-processing, 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 the Cache API...

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

...Check for caches objects in window s.

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 a 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 requested by the 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 this article on the fetch API for an introduction to the Request object.

Bulk cache requests can be added 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 a 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.
});
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 adds the request address as well as 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 the cache 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 see 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"
}
*/

For more information on the use of Response objects, you can refer to the fetch API article.

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, the/page/1 request data is no longer 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()Returned is also a Promise. 

Delete a cached object

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

caches.delete('test-cache').then(function() { 
  console.log('Cache successfully deleted!'); 
});

Large number of ways to delete old cached data:

// Assume `CACHE_NAME` is the name of the new cache
// Clear the old cache now
var CACHE_NAME = 'version-8';

// ...

caches.keys().then(function(cacheNames) {
  return Promise.all(
    cacheNames.map(function(cacheName) {
      if(cacheName != CACHE_NAME) {
        return caches.delete(cacheName);
      }
    })
  );
});

Want to be a 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 s will soon use this caching technology to speed up their operations.

Posted by (RL)Ian on Tue, 04 Jun 2019 10:12:04 -0700