HTTP cache ServiceWorker cacheStorage
The purpose of this article is to record my understanding of HTTP caching mechanism and the caching mechanism of ServiceWorker's cacheStorage
At present, I am still in the process of understanding ServiceWorker, and there may be many errors. Welcome to point out.
Browser Cache
Browser cache refers to the general name of the transmission mechanism used by the browser side to save data locally and read quickly to avoid duplicate resource requests.
Open the Chrome browser and enter the developer tool. In Application, you will find HTTP file cache, LocalStroage, SessionStorage, indexDB, Web SQL, cookies, CacheStorage and Application Cache.
Only HTTP file cache and Application Cache are introduced here
HTTP file cache
HTTP file caching is a browser file level caching mechanism based on the HTTP protocol. This mechanism determines whether the browser will update the file or read the file locally when the file is repeatedly requested.
The flow chart is as follows:
Flow chart step description:
- The browser will query first
Cache-Control
To determine whether the content is expired. If it is not expired, read the cache file directly and do not send an HTTP request. Otherwise, go to step 2 - The browser judges whether the response header of the last file has
Etag
, if any, together with If-None-Match
Send the request together, which is judged by the server Etag
, if not modified, return 304, if modified, return 200, otherwise go to step 3 - The browser judges whether the response header of the last file has
Last-Modified
, if any, together with If-Modified-Since
Send the request together, which is judged by the server Last-Modified
, 200 if invalid, 304 if not invalid Etag
and Last-Modified
None, 200
Supplementary notes: Cache-Control
Follow Expires
Is similar, but the former refers to the relative expiration time, and the latter refers to the absolute expiration time. If both are set at the same time, only Cache-Control
take effect
Calculation formula of cache duration: cache duration=response time+cache life - current time
Response time refers to the time when the browser receives the response from the server
For more information, see my other blog post: Here
cacheStorage
If you know something about PWA, you should know that the offline capability of PWA is provided by cacheStorage, so this part is also an important part.
Before introducing cacheStorage, let's introduce Application Cache.
Application Cache is a file level caching mechanism that allows browsers to selectively store static resources locally through manifest configuration files. When the page is opened after the second time, the resources will selectively read the files in the local Application Cache according to the manifest configuration description. The main advantages are: 1. offline access; 2. Fast loading speed; 3. The server load is small. However, the disadvantages are also obvious, including: 1. The standard has been abandoned; Incompatible with mainstream (mobile) browsers; 3. The capacity is only 5MB; 4. When resources fail, updates also fail; 5. Manifest should be the same source, etc
Here we mention RAIL, a user centered performance model. From here, you can see that Application Cache does not conform to RAIL
Finally, we can talk about cacheStorage
Google strongly promotes PWA and the technologies it supports, including ServiceWorker. CacheStorage is defined in the ServiceWorker specification and is used to save the Cache object declared by each ServiceWorker.
CacheStorage has a cache object built in the Chrome browser globally. It directly operates the cache object through five core API methods, as follows:
- Caches. match(): matches the Cache object containing the string in the key, and returns a Promise object
- Caches. has(): Check whether cache objects are included. If yes, a Promise object is returned
- Caches. open(): Open or create a Cache object and return a Promise object
- Caches. delete(): Successfully find and delete the Cache object and return a Promise object, otherwise return false
- Caches. keys (): traverse all Cache objects, and return a Promise object when any string in keys is contained
To understand cacheStorage, you need to have a deep understanding of ServiceWorker. Like WebWorker, ServiceWorker runs JavaScript as an independent thread in the browser background and communicates between pages through the message and postMessage methods. Native applications on the mobile end generally have the ability to push messages, use offline, and update automatically. If ServiceWorker is used, Web applications can also have similar capabilities.
When using ServiceWorker, you usually need to register a ServiceWorker JavaScript script first, and then write cache control methods in it. The following figure shows the life cycle of ServiceWorker running
Register ServiceWorker
if(navigator.serviceWorker){ navigator.serviceWorker.register('./ sw.js').then(function(registration){ Console. log ('sw registration succeeded '); }).catch(function(e){ Console. log ('sw registration failed '); }); }
Cache list in sw.js
let cacheList = ['index.js','index.css'];
Register the cache list to cacheStorage and use caches for management
this.addEventListener('install', function(event){ event.waitUntil( caches.open('indexCache').then(function(cache){ return caches.addAll(cacheList); }) ); });
Listen to the fetch method of ServiceWorker. If there is a response, use the response. Otherwise, read the cache
this.addEventListener('fetch', function(event){ event.respondWith(cacnes.match(event.request).then(function(response){ if(response){ return response; } let responseToCache = response.clone(); caches.open('indexCache').then(function(cache){ cache.put(event.request, responseToCache); }); })); });
For more information about ServiceWorker, see: Here
summary
Through horizontal understanding of HTTP file caching mechanism and ServiceWorker's cacheStorage, we can know that the former is a client based caching strategy, which is relatively fixed, while the latter is a page based caching strategy, which is extremely free and customizable.
There is not much content, and that's about it
This article is written by Chakhsu Lau Creation, adoption Knowledge Sharing Attribution 4.0 International License Agreement.
All articles on this website are original or translated by this website, except for the reprint/source. Please sign your name before reprinting.