Browser cache background

Because HTTP is a stateless protocol, every action a user takes on the browser is sent to the server, which cannot remember to track and record the action, so that the same action triggers a request, which imposes a significant performance cost on network communication.

An HTTP Cookie (also known as a Web Cookie or browser Cookie) is a small piece of data that a server sends to a user’s browser and keeps locally. It is carried and sent to the server the next time the browser makes a request to the same server. Typically, it is used to tell the server whether two requests are from the same browser, such as to keep the user logged in. Cookies make it possible to record stable state information over stateless HTTP protocols.

Cookies were once used to store data on the client side. As there was no other suitable storage method at that time, cookies were used as the only storage method. However, as modern browsers began to support a variety of storage methods, cookies gradually fell into disuse. Since the Cookie is specified by the server, each browser request carries the Cookie data, incurring additional performance overhead (especially in a mobile environment). New browser apis already allow developers to store data locally directly, such as using the Web Storage API (LocalStorage and SeeionStorage) or IndexedDB

Two. Cache implementation

1.Cookie

What a cookie does is the server labels you, and then every time you make a request to the server, the cookie recognizes you.

Cookie stored on the client: A cookie is a small piece of data that the server sends to the user’s browser and keeps locally. It is carried and sent to the server the next time the browser makes a request to the same server.

Applicable scenario

  • Session state management (such as user login status, shopping cart, game score, or other information that needs to be logged)
  • Personalization (such as user-defined Settings, themes, etc.)
  • Browser behavior tracking (e.g. tracking and analyzing user behavior, etc.)

Common use

(1) Set-cookie in HTTP response header

Set-Cookie: id=a3fWa; Expires=Wed, 21 Oct 2015 07:28:00 GMT;
Copy the code

(2) Cookie can be read and written in JS through document.cookie and displayed in the form of key-value pairs

// Encapsulate a cookie object var manageCookie={setCookie:function(name,value,time){// Set the cookie function document.cookie=name+'='+value+'; max-age='+time;
	  		returnthis; }, removeCookie:function(name){// Function to remove cookiesreturn this.setCookie(name,' ',-1);
	  	},
	  	getCookie:function(name,callback){
	  		var allCookieArr=document.cookie.split('; '); // Split each cookie into an array with a semicolon followed by a space console.log(document.cookie); var len=allCookieArr.length;for(var i=0; i<len; i++){ var itemCookieArr=allCookieArr[i].split('='); // Separate name from valueif(itemCookieArr[0]==name){
	  				callback(itemCookieArr[1]);
	  				return this;
	  			}
	  		}
	  		// callback(undefined);
	  		return this;
	  	}
	  }
	  manageCookie
	  .setCookie('color'.'red'.'10000')
	  .setCookie('nihao'.'buhao'.'10000')
	  .getCookie('nihao',aa);

	  function aa(data){
	  	console.log(data);
	  }
Copy the code

disadvantage

  • For example, the shopping cart function of e-commerce website has a large amount of information and a complex structure, so it is impossible to transmit so much information through simple cookie mechanism. Besides, it should be known that the cookie field is stored in HTTP header. Even if it can carry such information, it will consume a lot of bandwidth. Comparison consumes network resources.

security

  • Session hijacking and XSS: Cookies are commonly used in Web applications to tag users or authorize sessions. Therefore, if the cookies of Web applications are stolen, the sessions of authorized users may be attacked. Common ways to steal cookies include social engineering attacks and XSS attacks that exploit application vulnerabilities.

HttpOnly cookies can mitigate some of these attacks by preventing JavaScript from accessing them. Such as:

Set-Cookie: id=a3fWa; Expires=Wed, 21 Oct 2015 07:28:00 GMT; Secure; HttpOnly
Copy the code
  • Cross-site Request Forgery (CSRF) Wikipedia already gives a good example of CSRF. An image in an insecure chat room or forum, for example, is actually a request to your bank’s server to withdraw cash. If you are interested, please explore

2.session

Session is a data structure and another mechanism for recording the session status between the server and the client. It is implemented based on cookies. The session is stored on the server and the sessionId is stored in the cookie of the client.

It is designed by the developer of the website, so it can carry all kinds of data. As long as the cookie of the client sends a unique session ID, the server can find the corresponding session and recognize the client.

Session can be used with cookies to solve small capacity, for example, a cookie stores such a variable sessionID= XXXX, just send this cookie to the server, and then the server finds the corresponding session through this ID, The session is a data structure that stores details such as the user’s shopping cart, which the server can use to return to the user’s customized web page, effectively solving the problem of tracking the user

disadvantage
  • The more things a Session holds, the more memory it occupies on the server. The server with a large number of online users will have a high memory pressure. Therefore, sessions generally have an expiration time. You might be faced with re-logging in and so on.

  • Depend on cookie(sessionID stored in cookie). If cookie is disabled, url rewriting will be used, which is not secure

  • Creating Session variables is very arbitrary and can be called at any time and does not require the developer to do precise processing, so excessive use of Session variables will result in unreadable and bad code.

3.LocalStorage

The read-only localStorage property allows you to access a Document source (Origin) object Storage; The stored data is saved in the browser session. LocalStorage is similar to sessionStorage, but the difference lies in that: Data stored in localStorage can be retained for a long time. When the page session ends — that is, when the page is closed, the data stored in sessionStorage is erased.

The characteristics of

  • The saved data exists for a long time, and the next time you visit the site, the page can read the previously saved data directly.
  • The size is about 5M
  • It is used only on the client and does not communicate with the server
  • Good interface encapsulation

Applicable scenario

It is generally used to cache some data in the front end. The data is generally used only in the front end and not in the back end, so it is not necessary to send it to the back end every time. (or front-end to do statistics, back-end just a statistical result, etc.)

For example, some websites provide an editor, with its own draft function, every few seconds or minutes automatically save the current editing content, refresh the page, or turn off the browser to reopen the editing page can automatically restore the previous editing content. This information is suitable to be stored in localStorage.

Common use

The following code snippet accesses the local Storage object under the current domain name and adds a data item via storage.setitem (). localStorage.setItem(‘myCat’, ‘Tom’);

// This syntax is used for readinglocalStorage, as follows:let cat = localStorage.getItem('myCat');
Copy the code
// This syntax is used for removallocalStorage, as follows:localStorage.removeItem('myCat');
Copy the code
This syntax is used to remove alllocalStorage, as follows:localStorage.clear();
Copy the code

3.sessionStorage

The sessionStorage property allows you to access a sessionStorage object corresponding to the current source. It is similar to localStorage except that data stored in localStorage does not have an expiration date, while data stored in sessionStorage is cleared when the page session ends.

The characteristics of

  • The page session remains as long as the browser is open, and the original page session remains when the page is reloaded or restored.
  • Top-level browsing is copied when a new TAB or window opens a page
  • The context of the session acts as the context of the new session, unlike session cookies.
  • Opening multiple Tabs pages of the same URL creates their own sessionStorage.
  • Closing the corresponding browser TAB clears the corresponding sessionStorage.
  • The size is about 5M
  • It is used only on the client and does not communicate with the server

Applicable scenario

SessionStorage is more suitable for storing life-cycle and session-level information that it synchronizes. This information only applies to the current session and needs to be updated or released when you start a new session. For example, the sessionStorage of Weibo is mainly to store the record of your session (by topic).

Common use

The following example will automatically save the contents of a text entry field, and if the browser is refreshed by accident, the contents of the text entry field will be restored so that the written content is not lost.

// Get the text input boxlet field = document.getElementById("field"); // Check for the presence of an autosave key (this will be present if the page is accidentally refreshed)if (sessionStorage.getItem("autosave"Field. Value = sessionStorage.getitem ();"autosave"); } // Listen for the change event field.adDeventListener ("change".function() {// Save the result to the sessionStorage object sessionStorage.setitem ("autosave", field.value);
});
Copy the code

4.indexedDB

IndexedDB is an underlying API used by clients to store large amounts of structured data (including files/binary Large objects (BloBs)). The API uses indexes to enable a high-performance search of this data. While Web Storage is useful for storing smaller amounts of data, this approach is less useful for storing larger amounts of structured data. IndexedDB provides a solution. In theory, IndexedDB has no upper storage limit (generally no less than 250MB).

The characteristics of

  • Same Origin Policy Like most Web storage solutions, IndexedDB complies with the same origin policy. So when you store data in one domain, you can’t store data in another domain.

  • Synchronous and asynchronous Operations performed with IndexedDB are performed asynchronously so as not to block applications. IndexedDB initially included synchronous and asynchronous apis. The synchronization API for Web Workers only has been removed from the specification because it is not clear whether it is needed. But if Web developers have enough needs, they can reintroduce the synchronization API.

  • Storage limitations and reclamation standards Many Web technologies store various types of data on the client side, that is, on a local disk. IndexedDB is the most common one. The process by which the browser calculates the space allocated to the Web data store and what to delete when that limit is reached is not simple and varies from browser to browser.

  • Support for Transactions IndexedDB supports transactions, which means that if one of the steps fails, the entire transaction is cancelled and the database is rolled back to the state before the transaction occurred, without overwriting only a portion of the data

Common use

See as an example, how to make the store image and file: with indexedDB hacks.mozilla.org/2012/02/sav…

Three. Cache implementation comparison

Cache way Store address Storage mode and size The life cycle scope Service communication
cookie The client String or text (<= 4KB) If the client requests server generation, you can set the expiration period. If the expiration period is not set or generated only on the client, the expiration period expires after the client is shut down by default. DomainPathThe identity defines the * scope of the Cookie: * which urls the Cookie should be sent to.DomainThe identity specifies which hosts can accept cookies. If this parameter is not specified, it is used by defaultHost of the current document(Does not contain subdomain names). If you specifyDomain, generally contains subdomain names. This is carried each time in HTTP headers, and using cookies to store too much data can cause performance problems
session The service side Object of any type (unlimited size) The session expiration time can be set on the server. If the client does not actively access the session during this period, the session is invalid. The sessionID stored by the client is the same as the cookie life cycle With cookies Participate in with cookies
LocalStorage The client Can only store string types, complex objects are handled with ES6’s JSON object stringify and parse (<=5Mb) Save permanently unless actively removed Restricted to the document source level. The document source is identified by protocol, host name, and port (must be the same origin). Don’t participate in
sessionStorage The client Can only store string types, complex objects are handled with ES6’s JSON object stringify and parse (<=5Mb) This parameter is valid only in the current session and is cleared after you close the page or browser More strictly, restrict it to the document source level (cognate). It is also required to be in the same window (i.e. the browser TAB), otherwise the sessionStorage data cannot be shared. Don’t participate in
indexedDB The client Object of any type (unlimited size) Save permanently unless actively removed Restricted to the document source that contains them, each database corresponds to the domain name that created the database, and two same-origin Web pages can access each other’s data, but non-same-origin pages cannot Don’t participate in

The resources

MDN | HTTP cookie

HTML Living Standard

Cookie, LocalStorage and SessionStorage