Home > Web Front-end > JS Tutorial > body text

Sample code sharing of how Javascript obtains cache and clears cache API

黄舟
Release: 2017-05-26 09:58:56
Original
1957 people have browsed it

This article mainly introduces the detailed explanationJavascriptGetCache and Clear CacheAPI. The editor thinks it is quite good. Now I share it with everyone and also give Let’s all use it as a reference. Let’s follow the editor and take a look.

The advantage of JavaScript ServiceWorker API is that it allows web developers to easily control caching. Although using technologies such as ETags is also a technology for controlling cache, pressing to use JavaScript allows the program to control the cache function more powerfully and freely. Of course, being powerful has its advantages and disadvantages - you need to deal with the aftermath, and the so-called aftermath means cleaning the cache.

Let’s take a look at how to create a cache object , add a request to the cache cache data , and delete a request from the cache Cache data, and finally how to completely delete the cache.

Determine the browser's support for the cache object cache API

Check whether the browser supports the Cache API...

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

...Check whether there is a cache object in the window.

Create a cache object

The method 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) {
 // 缓存创建完成,现在就可以访问了
});
Copy after login

This caches.open method returns a Promise, in which the cache object is newly created. If it has been created before, it will not be re-created.

Add cache data

For this type of cache, you can think of it as a Request objectarray, the response data obtained by the Request request The key value will be stored in the cache object. There are two methods 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!
  });
});
Copy after login

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. Add a single address using the add method:

caches.open('test-cache').then(function(cache) {
 cache.add('/page/1'); // "/page/1" 地址将会被请求,响应数据会缓存起来。
});
add()方法还可以接受一个自定义的Request:

caches.open('test-cache').then(function(cache) {
 cache.add(new Request('/page/1', { /* 请求参数 */ }));
});
//跟add()方法很相似,put()方法也可以添加请求地址,同时添加它的响应数据:

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

Access cache data

To view the changed request data, we can use the key## in the cache object #s() method to get all cached Request objects in 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"
}
*/
Copy after login

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"
}
*/
Copy after login

For the usage and detailed information of Response object, you can refer to the fetch API article.

Delete data in the 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');
});
Copy after login

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

Get the cache name in the existing cache

To get the name of the cached 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"]
});
Copy after login

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


Delete a cache object

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

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

A lot How to delete old cached data:

// 假设`CACHE_NAME`是新的缓存的名称
// 现在清除旧的缓存
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);
   }
  })
 );
});
Copy after login
Want to become a service worker expert? The code above is worth adding to your repository.

Firefox and Google Chrome both support service workers. I believe that more websites and apps will soon use this caching technology to improve running speed.

The above is the detailed content of Sample code sharing of how Javascript obtains cache and clears cache API. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template