search
HomeWeb Front-endJS TutorialSample 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"
}
*/

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 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');
});

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"]
});

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!'); 
});

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);
   }
  })
 );
});

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!

Statement
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
Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The Evolution of JavaScript: Current Trends and Future ProspectsThe Evolution of JavaScript: Current Trends and Future ProspectsApr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.