


Sample code sharing of how Javascript obtains cache and clears cache API
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! }
...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) { // 缓存创建完成,现在就可以访问了 });
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! }); });
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); }); });
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" } */
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" } */
Delete data in the cache
To delete data from the cache, we can use thedelete() method in the cache object:
caches.open('test-cache').then(function(cache) { cache.delete('/page/1'); });
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"] });
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!'); });
// 假设`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); } }) ); });
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Which folder does the browser cache the video in? When we use the Internet browser every day, we often watch various online videos, such as watching music videos on YouTube or watching movies on Netflix. These videos will be cached by the browser during the loading process so that they can be loaded quickly when played again in the future. So the question is, in which folder are these cached videos actually stored? Different browsers store cached video folders in different locations. Below we will introduce several common browsers and their

DNS (DomainNameSystem) is a system used on the Internet to convert domain names into corresponding IP addresses. In Linux systems, DNS caching is a mechanism that stores the mapping relationship between domain names and IP addresses locally, which can increase the speed of domain name resolution and reduce the burden on the DNS server. DNS caching allows the system to quickly retrieve the IP address when subsequently accessing the same domain name without having to issue a query request to the DNS server each time, thereby improving network performance and efficiency. This article will discuss with you how to view and refresh the DNS cache on Linux, as well as related details and sample code. Importance of DNS Caching In Linux systems, DNS caching plays a key role. its existence

A Beginner's Guide to Guava Cache: Speed Up Your Applications Guava Cache is a high-performance in-memory caching library that can significantly improve application performance. It provides a variety of caching strategies, including LRU (least recently used), LFU (least recently used), and TTL (time to live). 1. Install Guava cache and add the dependency of Guava cache library to your project. com.goog

Title: Caching mechanism and code examples of HTML files Introduction: When writing web pages, we often encounter browser cache problems. This article will introduce the caching mechanism of HTML files in detail and provide some specific code examples to help readers better understand and apply this mechanism. 1. Browser caching principle In the browser, whenever a web page is accessed, the browser will first check whether there is a copy of the web page in the cache. If there is, the web page content is obtained directly from the cache. This is the basic principle of browser caching. Benefits of browser caching mechanism

There is a close interaction between the CPU (central processing unit), memory (random access memory), and cache, which together form a critical component of a computer system. The coordination between them ensures the normal operation and efficient performance of the computer. As the brain of the computer, the CPU is responsible for executing various instructions and data processing; the memory is used to temporarily store data and programs, providing fast read and write access speeds; and the cache plays a buffering role, speeding up data access speed and improving The computer's CPU is the core component of the computer and is responsible for executing various instructions, arithmetic operations, and logical operations. It is called the "brain" of the computer and plays an important role in processing data and performing tasks. Memory is an important storage device in a computer.

PHPAPCu (replacement of php cache) is an opcode cache and data cache module that accelerates PHP applications. Understanding its advanced features is crucial to utilizing its full potential. 1. Batch operation: APCu provides a batch operation method that can process a large number of key-value pairs at the same time. This is useful for large-scale cache clearing or updates. //Get cache keys in batches $values=apcu_fetch(["key1","key2","key3"]); //Clear cache keys in batches apcu_delete(["key1","key2","key3"]);2 .Set cache expiration time: APCu allows you to set an expiration time for cache items so that they automatically expire after a specified time.

How to Export Browser Cache Videos With the rapid development of the Internet, videos have become an indispensable part of people's daily lives. When browsing the web, we often encounter video content that we want to save or share, but sometimes we cannot find the source of the video files because they may only exist in the browser's cache. So, how do you export videos from your browser cache? This article will introduce you to several common methods. First, we need to clarify a concept, namely browser cache. The browser cache is used by the browser to improve user experience.

SpringBoot is a popular Java framework known for its ease of use and rapid development. However, as the complexity of the application increases, performance issues can become a bottleneck. In order to help you create a springBoot application as fast as the wind, this article will share some practical performance optimization tips. Optimize startup time Application startup time is one of the key factors of user experience. SpringBoot provides several ways to optimize startup time, such as using caching, reducing log output, and optimizing classpath scanning. You can do this by setting spring.main.lazy-initialization in the application.properties file
