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 theChrome 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 the ETag, determine whether the file is modified, if modified, take the If-none-match send request, return 200 or 304, otherwise enter the next step
- Judge Last-modified, determine whether the file exceeds the maximum cache time, then take the if-modified-since send request, return 200 or 304, otherwise directly without sending the 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
var db = OpenDatabase (' MyDatabase ', ' 2.0 ', my db ', 2 * 1024);
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 * 1024x768 * 1024x768); 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 * 1024x768); 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 * 1024x768); 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 and E_log are external variables });
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.row S.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.
Asynchronous API
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.
-Idbfactory provides access to the database. This is the interface implemented by the global object IndexedDB, and is therefore the gateway to the API. -Idbcursor traverse the object storage space and index. -Idbcursorwithvalue iterates through the object storage space and index and returns the current value of the cursor. -Idbdatabase represents a connection to the database. Only this connection can be used to get a database transaction. -Idbenvironment provides access to the client database. It is implemented by the Window object. -Idbindex provides access to the index metadata. -Idbkeyrange defines the range of keys. -Idbobjectstore represents an object storage space. -Idbopendbrequest represents a request to open a database. -Idbrequest provides access to database asynchronous request results and database. This is also what you get when you invoke an asynchronous method. -IDbTransaction represents a transaction. You create a transaction on the database, specify its scope (for example, which object storage space you want to access), and determine the type of access you want (read-only or write). -Idbversionchangeevent indicates that the version number of the database has changed.
Synchronization API
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.js
http://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 |
IE9 or more |
5M |
More than 8 Firefox |
5.24M |
Opera |
2M |
Safari/webkit |
2.6M |
Localstorage Core API:localStorage.setItem (key, value) //Set record Localstorage.getitem (key) // Get record Localstorage.removeitem (key) //delete the domain under the single record Localstorage.clear () //delete all records under the domain name
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
CACHE manifest#version 1.0cache:clock.cssclock.js
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 '; break;};
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 (); The fetch was successful, swap in the new cache.}
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 ()
If the cache object is included, a Promise object is returned.
Cachestorage.open ()
Opens a cache object and 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, it 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 () { somecachesetupfunction ();});;
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 () { return Caches.match ('/sw-test/gallery/mylittlevader.jpg ');});
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:\Users\your-account-name\AppData\Local\Google\Chrome\User data\default\", and Firefox data is stored in the "C:\Users\ Your-account-name\appdata\local\mozilla\firefox\profiles\ "directory.
- The cookie file is stored in the Documents and Settings\username\cookie\ 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
Analysis of 9 large browser-side caching mechanism