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...
1 2 3 |
|
...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:
1 2 3 |
|
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:
1 2 3 4 5 6 |
|
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
|
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
|
Delete data in the cache
To delete data from the cache, we can use thedelete() method in the cache object:
1 2 3 |
|
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:1 2 3 |
|
Delete a cache object
To delete a cache object, you only need the cache key name:1 2 3 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
|
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!