Browser cache (Browser Caching) is a browser-side save data for fast read or avoid duplicate resource request optimization mechanism, effective cache use can avoid duplicate network requests and the browser quickly read local data, the overall acceleration of the page display to the user. Browser-side caching mechanism of a number of types, the overall sum of nine, here detailed analysis of the nine kinds of caching mechanism of the principle and usage scenarios. Open the browser's debug mode->resources to the left there are 8 kinds of browser caching mechanism.
First, HTTP caching
HTTP caching is a browser file-level caching mechanism based on the HTTP protocol . In the case of repeated requests for files, the browser can determine whether to request files from the server side or to read the files locally based on the protocol header, and the frames in the Chrome console shows the browser's HTTP file-level cache. The following is the entire mechanism flow of browser caching. Mainly for repeated HTTP requests, in the case of a cache to determine the process is mainly divided into 3 steps:
- Judge expires, if not expired, read the HTTP cache file directly, do not send an HTTP request, otherwise go to the next step
- Determine if there is an etag, then take the If-none-match send request, unmodified return 304, modify return 200, otherwise go to the next step
- Determine if there is a last-modified, there is a if-modified-since send request, invalid return 200, effectively return 304 (unmodified--not modified), or directly to the server request
If the ETag and last-modified are judged, even if the return 304 has at least one HTTP request, only 304 of the returned content is returned, not the file contents. Therefore, reasonable design and implementation of expires parameters can reduce the number of browser requests.
Second, Websql
Websql This approach is only supported by newer chrome browsers and appears as an independent specification, with the following features
- The Web SQL database API is not actually part of the HTML5 specification;
- Existed before the HTML5, and was a separate norm;
- It is to store data in the form of a database in the client, according to the requirements to read;
- the difference with storage is that both storage and cookies exist in the form of key-value pairs ;
- Web SQL is easy to retrieve, allowing SQL statement query;
- Let the browser implement small database storage function;
- This database is integrated in the browser, the current mainstream browser has basically been supported;
The Websql API mainly consists of three core methods:
- OpenDatabase: This method creates a database object using an existing database or creating a new database.
- Transaction: This method allows us to control the transaction commit or rollback, depending on the situation.
- ExecuteSQL: This method is used to execute a real SQL query.
The OpenDatabase method can open a database that already exists and does not exist to create
The five parameters in Opendatabasek are: database name, version number, description, database size, create callback. Creating a callback does not create a database either.
The Database.transaction () function is used to query, ExecuteSQL () to execute SQL statements
For example, CREATE table T1 in the MyDatabase database:
var db = openDatabase(‘ mydatabase ‘, ‘1.0‘, ‘Test DB‘, 2 * 1024 * 1024); db.transaction(function (tx) { tx.executeSql(‘CREATE TABLE IF NOT EXISTS t1 (id unique, log)‘);
Insert operation
var db = openDatabase(‘mydatabase‘, ‘2.0‘, my db‘, 2 * 1024); db.transaction(function (tx) { tx.executeSql(‘CREATE TABLE IF NOT EXISTS t1 (id unique, log)‘); tx.executeSql(‘INSERT INTO t1 (id, log) VALUES (1, "foobar")‘); tx.executeSql(‘INSERT INTO t1 (id, log) VALUES (2, "logmsg")‘);
When inserting new records, we can also pass dynamic values, such as:
var db = openDatabase(‘ mydatabase ‘, ‘2.0‘, ‘my db‘, 2 * 1024); db.transaction(function (tx) { tx.executeSql(‘CREATE TABLE IF NOT EXISTS t1 (id unique, log)‘); tx.executeSql(‘INSERT INTO t1 (id,log) VALUES (?, ?‘), [e_id, e_log]; //e_id和e_log是外部变量
Read operation, if you want to read a record that already exists, we use a callback to capture the result:
var db = openDatabase(mydatabase, ‘2.0‘, ‘my db‘, 2*1024); db.transaction(function (tx) { tx.executeSql(‘CREATE TABLE IF NOT EXISTS t1 (id unique, log)‘); tx.executeSql(‘INSERT INTO t1 (id, log) VALUES (1, "foobar")‘); tx.executeSql(‘INSERT INTO t1 (id, log) VALUES (2, "logmsg")‘); }); db.transaction(function (tx) { tx.executeSql(‘SELECT * FROM t1, [], function (tx, results) { var len = results.rows.length, i; msg = "<p>Found rows: " + len + "</p>"; document.querySelector(‘#status‘).innerHTML += msg; for (i = 0; i < len; i++){ alert(results.rows.item(i).log ); } }, null);
Third, Indexdb
IndexedDB is an API to enable high-performance retrieval of data on the client side by storing a significant amount of structured data. Although DOM storage is useful for storing small amounts of data, it can be too much for storing large amounts of structured data. IndexedDB provides such a solution. IndexedDB provides separate APIs for synchronous and asynchronous access, respectively. The synchronization API was intended to be used only for internal use by Web Workers, but has not yet been implemented by any browser. Asynchronous APIs can be used both inside and outside the Web Workers, and the browser may have a 50M size limit on the indexdb, and the average user holds a large amount of user data and requires a scene between the data and the search needs.
When the asynchronous API method call is finished, it returns immediately without blocking the calling thread. To access the database asynchronously, invoke the open () method of the Window object's IndexedDB property. The method returns a Idbrequest object (Idbopendbrequest), and the asynchronous operation communicates with the caller by triggering an event on the Idbrequest object.
The specification also defines a synchronous version of the API. The synchronization API is not yet implemented in any browser. It was originally intended to be used with webwork.
http://mxr.mozilla.org/mozilla-central/source/modules/libpref/src/init/all.jshttp://caniuse.com/#feat =INDEXEDDB
Iv. Cookies
Cookies (or cookies) are data (usually encrypted) that are stored on the user's local terminal in order to identify the user and track the session. Cookies are typically sent to the server side by the head in an HTTP request. A cookie record is mainly composed of key, value, domain, expiration time, size, and the general user saves the user's authentication information. The maximum length of the cookie and the number of domain names are determined by different browsers, as follows:
Browser |
number of support domains |
Maximum length |
IE7 or more |
50 x |
4095B |
Firefox |
50 x |
4097B |
Opera |
30 x |
4096B |
Safari/webkit |
Unlimited |
4097B |
The cookie information between different domain names is independent, and if you need to set up a share you can set the cookie path and domain on the server side for sharing. The browser can also use Document.cookie to get the cookie, and the value of the cookie can be easily read/set by the Js browser side.
Https://github.com/component/cookie/blob/master/index.js
Wu, Localstorage
Localstorage is a new local caching scheme for HTML5, which is used more often to store the data returned by Ajax and to speed up rendering the next time the page is opened.
Browser |
Maximum length |
IE8 or more |
5M |
More than 8 Firefox |
5.24M |
Opera |
2M |
Safari/webkit |
2.6M |
//localStorage核心API: localStorage.setItem(key, value) //设置记录 localStorage.getItem(key) //获取记录 localStorage.removeItem(key) //删除该域名下单条记录 localStorage.clear()
It is worth noting that the localstorage size is limited, is not suitable for storing too much data, if the data storage exceeds the maximum limit will be an error, and remove the first saved data.
Https://github.com/machao/localStorage
Liu, Sessionstorage
Sessionstorage and Localstorage are similar, but browser shutdown is all removed, the API and Localstorage are the same, and fewer are used in actual projects.
VII. Application Cache
Application Cahce is to put most of the picture resources, JS, CSS and other static resources in the manifest file configuration. Reads a local file or requests a server file from a manifest file when the page is opened. Offline access is becoming increasingly important for web-based applications. Although all browsers have caching mechanisms, they are unreliable and do not always work as expected. HTML5 uses the Applicationcache interface to solve some of the challenges that are caused by offline. The premise is that the Web page you need to visit has been visited at least once online. Using the Cache interface brings you the following three benefits for your application:
- Offline Browsing – Users can browse your entire website while offline
- Speed – The cache resource is a local resource, so it loads faster.
- Less server load – The browser downloads resources only from the server that has changed.
A simple offline page consists mainly of the following sections:
Index.html
Clock.manifest
Clock.js and CLOCK.CSS for separate documents. It is also important to note that the cache is updated. In the program, you can access the browser's app cache via the Window.applicationcache object. You can view the Status property to get the current state of the cache:
var appCache = window.applicationCache; switch (appCache.status) { case appCache.UNCACHED: // UNCACHED == 0 return ‘UNCACHED‘; break; case appCache.IDLE: // IDLE == 1 return ‘IDLE‘; break; case appCache.CHECKING: // CHECKING == 2 return ‘CHECKING‘; break; case appCache.DOWNLOADING: // DOWNLOADING == 3 return ‘DOWNLOADING‘; break; case appCache.UPDATEREADY: // UPDATEREADY == 4 return ‘UPDATEREADY‘; break; case appCache.OBSOLETE: // OBSOLETE == 5 return ‘OBSOLETE‘; break; default: return ‘UKNOWN CACHE STATUS‘;
In order to update the cache programmatically, first call Applicationcache.update (). This will attempt to update the user's cache (requires that the manifest file has changed). Finally, when Applicationcache.status is in the Updateready state, call Applicationcache.swapcache () and the old cache is replaced with a new.
var appCache = window.applicationCache; appCache.update(); // Attempt to update the user’s cache. … if (appCache.status == window.applicationCache.UPDATEREADY) { appCache.swapCache();
This is done by updating the Menifest file to control other file updates.
Eight, CachestorageCachestorage is defined in the specification of Serviceworker. Cachestorage can save each Serverworker declared cache object, Cachestorage has the open, match, has, delete, keys five core methods, you can respond differently to different matches of the cache object.
Cachestorage.has () Returns a Promise object if it contains a cache object. Cachestorage.open () opens a cache object, it returns a Promise object. cachestorage.delete () deletes the cache object, returns a Promise object successfully, or returns false. Cachestorage.keys () contains any one of the strings in the keys and returns a Promise object. Cachestorage.delete () matches the cache object containing the string in key and returns a Promise object.
caches.has(‘v1‘).then(function() { caches.open(‘v1‘).then(function(cache) { return cache.addAll(myAssets); }); }).catch(function() {
var response; var cachedResponse = caches.match(event.request).catch(function() { return fetch(event.request); }).then(function(r) { response = r; caches.open(‘v1‘).then(function(cache) { cache.put(event.request, response); }); return response.clone(); }).catch(function() {
then.addEventListener(‘activate‘, function(event) { var cacheWhitelist = [‘v2‘]; event.waitUntil( caches.keys().then(function(keyList) { return Promise.all(keyList.map(function(key) { if (cacheWhitelist.indexOf(key) === -1) { return caches.delete(keyList[i]); } }); })
Https://developer.mozilla.org/en-US/docs/Web/API/CacheStorage
Nine, Flash cacheThis approach is basically not used, this method is mainly based on the Flash has read and write browser-side local directory function, but also can provide a call to JS API, the page can be called by JS Flash to read and write to the specific disk directory, to achieve the purpose of local data cache.
Note PS
- The data of the Web storage/web SQL database/indexed database is stored in the browser's corresponding user profile directory, in Windows 7, for example, Chrome's data Stored under "C:usersyour-account-nameappdatalocalgooglechromeuser datadefault" and Firefox's data is stored in the "C: Usersyour-account-nameappdatalocalmozillafirefoxprofiles "directory.
The cookie file is stored in the Documents and Settingsusernamecookie folder. The usual naming format is: [email protected].
More cache mechanisms are not compatible with mainstream browsers at the moment, but you can use the Polyfill method to handle
Browser-related caching methods mainly include these, specifically in conjunction with their own business scenarios to choose to use
9 in the browser-side cache