The advantage of the JavaScript ServiceWorker API is that it allows WEB developers to easily control caches. Although using technologies such as ETags is also a technology to control caches, using JavaScript allows programs to control caches more powerful and freely. Of course, strong has its advantages and disadvantages - you need to do after-care treatment. The so-called after-care treatment is to clean up the cache.
Let’s take a look at how to create a cache object, add request cache data in the cache, delete request cache data from the cache, and finally how to completely delete the cache.
Determine the browser's support for cache object cache API
Check whether the browser supports the Cache API...
if('caches' in window) { // Has support!}…Check whether there is a caches object in the window.
Create a cache object
The way to create a cache object is to use caches.open() and pass in the cache name:
caches.open('test-cache').then(function(cache) { // The cache is created and you can access it now});This caches.open method returns a Promise, and the cache object in it is newly created. If it has been created before, it will not be recreated.
Add cached data
For this type of cache, you can think of it as an array of Request objects, and the response data obtained by the Request request will be stored in the cache object by key value. There are two ways to add data to the cache: add and addAll. Use these two methods to add the address of the request to be cached. For an introduction to the Request object, you can refer to the fetch API article.
Use the addAll method to add cache requests in batches:
caches.open('test-cache').then(function(cache) { cache.addAll(['/', '/images/logo.png']) .then(function() { // Cached! });});This addAll method can accept an address array as a parameter, and the response data of these request addresses will be cached in the cache object. addAll returns a Promise. To add a single address, use the add method:
caches.open('test-cache').then(function(cache) { cache.add('/page/1'); // The "/page/1" address will be requested and the response data will be cached.});The add() method can also accept a custom Request:
caches.open('test-cache').then(function(cache) { cache.add(new Request('/page/1', { /* Request parameter*/ }));});It is very similar to the add() method. The put() method can also add the request address and add its response data at the same time:
fetch('/page/1').then(function(response) { return caches.open('test-cache').then(function(cache) { return cache.put('/page/1', response); });});Access 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 form:
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 the cached Request request, you can use the cache.match() or cache.matchAll() method:
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 about the usage and details of Response objects, you can refer to the fetch API article.
Delete data in the cache
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 be no more /page/1 request data in the cache.
Get the cache name 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() returns a promise.
Delete a cache object
To delete a cached object, you only need the cached key name:
caches.delete('test-cache').then(function() { console.log('Cache successfully deleted!'); });How to delete old cached data in large quantities:
// Assume `CACHE_NAME` is the name of the new cache // Now clear the old cache 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 become a service worker expert? The above code is worth putting in your library. Firefox and Google Chrome support service worker, and I believe that more websites and apps will use this caching technology to improve their running speed soon.
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.