Home  >  Article  >  Web Front-end  >  Summary of five key points of JS caching mechanism

Summary of five key points of JS caching mechanism

PHPz
PHPzOriginal
2024-01-23 08:12:211104browse

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

  1. 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');
  1. 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

  1. 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 {
  // 发送网络请求
}
  1. 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

  1. 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');
  1. 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

  1. 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>
  1. 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!

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
Previous article:js intercepts stringNext article:js intercepts string