Summary of five key points of JS caching mechanism
Knowledge review: five key points in the JS caching mechanism, specific code examples are required
Introduction: In front-end development, caching is important to improve web page performance One ring. The JavaScript caching mechanism refers to saving the acquired resources locally so that the cache can be directly used in subsequent accesses, thereby reducing resource loading time and network bandwidth consumption. This article will introduce the key points in the JS caching mechanism and provide specific code examples.
1. Cache type
- Strong cache
Strong cache is achieved by setting the Expires or Cache-Control field in the HTTP response header Caching mechanism. When the browser requests a resource, it will first check whether the resource exists in a local cache. If it exists and is still within the validity period, the cache will be used directly without sending a request.
Sample code:
// 设置缓存时间为1个小时 res.setHeader('Cache-Control', 'max-age=3600');
- Negotiation cache
Negotiation cache is set by setting If-Modified-Since or If-None- in the HTTP request header Match field to communicate with the server caching mechanism. When the browser requests a resource, it will first send the request to the server. The server compares the fields in the request header with the last modification time of the resource. If the resource has not changed, it returns status code 304 Not Modified and notifies the browser to use Local cache.
Sample code:
// 获取请求头中的If-Modified-Since字段 const ifModifiedSince = req.headers['if-modified-since']; // 获取资源的最后修改时间 const lastModified = fs.statSync(filepath).mtime.toUTCString(); // 比较请求头中的字段与最后修改时间 if (ifModifiedSince === lastModified) { res.statusCode = 304; // Not Modified res.end(); } else { res.setHeader('Last-Modified', lastModified); // 返回资源 res.end(file); }
2. Cache location
- Browser cache
Browser cache refers to the cache in the browser Local cache files. When the browser accesses the same resource, it will first check whether there is a cache file for the resource. If it exists, the cache will be used directly. Otherwise, a network request will be sent.
Sample code:
// 读取缓存 const cache = localStorage.getItem('cache'); // 判断缓存是否存在 if (cache) { // 使用缓存 } else { // 发送网络请求 }
- Server cache
Server cache refers to the cache file cached on the server side. When the browser requests a resource, the server checks whether a cache file exists for the resource, and if so, returns the cache file directly.
Sample code:
// 判断文件是否存在 if (fs.existsSync(filepath)) { // 返回缓存文件 } else { // 发送网络请求 }
3. Cache time control
- Cache time
Cache time refers to strong cache or negotiated cache The validity period can be set to different cache times according to needs.
Sample code:
// 设置缓存时间为1个小时 res.setHeader('Cache-Control', 'max-age=3600');
- Cache strategy
Cache strategy refers to setting different cache strategies based on resource type or resource path. Different caching strategies can be implemented using regular expressions or string matching.
Sample code:
// 设置图片资源的缓存时间为1个月 if (req.url.match(/.jpg|.png|.gif$/)) { res.setHeader('Cache-Control', 'max-age=2592000'); }
4. Cache update
- Version control
Version control refers to adding a version when requesting resources number, and the version number is updated when the resource changes. You can force the browser to reload the resource by updating the version number.
Sample code:
<!-- 添加版本号 --> <link rel="stylesheet" href="styles.css?v=1.0"> <script src="script.js?v=1.0"></script>
- Forced refresh
Forced refresh refers to telling the browser by setting the max-age of the Cache-Control field to 0 Update cache immediately.
Sample code:
// 强制刷新缓存 res.setHeader('Cache-Control', 'max-age=0');
5. Cache clearing
Cache clearing refers to manually deleting the browser’s local cache files or server-side cache files.
Sample code:
// 清除浏览器缓存 localStorage.removeItem('cache'); // 清除服务器缓存 fs.unlinkSync(filepath);
Summary: For common JS caching mechanisms in front-end development, we have introduced five key points, including cache type, cache location, cache time control, Cache updates and cache clearing. Mastering these key points can help us better understand and apply the caching mechanism, improve web page performance, and enhance user experience. I hope that the introduction of this article can be helpful to all readers.
The above is the detailed content of Summary of five key points of JS caching mechanism. For more information, please follow other related articles on the PHP Chinese website!

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr


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

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.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

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.
