@browser local storage ramble

create by db on 2019-6-21 11:30:54

Recently revised in 2019-7-6 22:50:24

Hello friends, if you think this article is good, please give a thumbs up or a star, your thumbs up and star are my motivation! Making the address

preface

I hear and I fogorget.

I see and I remember.

I do and I understand.

As a front-end code farmer, dealing with browsers every day, we have the browser data storage scheme how much understanding?

References:

  • The browser | making – ljianshu

  • Learn more about browser storage

  • Common cache technology | blog garden – drunk light

  • Rambling front-end cache | Xie Ziqiong

  • About several common front-end cache | CSDN “blank

The body of the

Front-end Cache Overview

The front-end cache is mainly divided into browser cache and HTTP cache. The general classification is shown in the figure below:

Local storage for the browser

Storing data on the browser side is very useful for us. It is equivalent to giving the browser memory function, which can record all the state information of the user and enhance the user experience. For example, when recording the login status of users, users can access it more quickly, instead of having to carry out tedious operations every time they log in.

Let’s talk briefly about the browser’s local storage mechanism.

Open Google Chrome, press F12 to open developer tools, select Application, and see your browser’s cache. As shown below:

The graph clearly shows the browser cache classification. In general, during the normal development process, the most common data storage schemes on the market are the following three:

  • Cookie
  • Web storage (localStorageandseesionStorage)
  • IndexedDB

As shown below:

So what’s the difference between these caches?

Cookie

Cookie Use Tutorial –>Novice tutorial

What is a Cookie

JavaScript is a script that runs on the client side, so you generally can’t set sessions because sessions are run on the server side. Cookies run on the client side, so you can use JS to set cookies.

Cookie is a browser-provided mechanism that provides JavaScript with the cookie property of the Document object. It can be controlled by JavaScript, not the nature of JavaScript itself. A cookie is a file stored on a user’s hard drive, usually corresponding to a domain name, that is made available when the browser accesses the domain name again. Therefore, cookies can span multiple web pages under a domain name, but cannot be used across multiple domains.

The advantages of the Cookie

The cookie mechanism stores information on the user’s hard disk and therefore can be used as a global variable, which is one of its greatest advantages. It can be used in the following situations.

  1. Save the user login status.
  2. Track user behavior.
  3. Customize the page.
  4. Create a shopping cart, such as taobaocookieRecords the user has browsed the goods, convenient for comparison at any time.

The disadvantage of the Cookie

Cookies can do some of the application, but there are many more functions that need global variables. The disadvantages of cookies mainly focus on security and privacy protection. It mainly includes the following:

  1. cookieMay be disabled. When a user is very privacy conscious, he is likely to disable the browsercookieFunction;
  2. cookieIs browser-specific. This means that even if you’re visiting the same page, it’s saved between different browserscookieThey can’t visit each other;
  3. cookieMay be deleted. Because eachcookieIs a file on the hard disk, so is likely to be deleted by the user;
  4. cookieSecurity is not high enough. All of thecookieAll files are recorded in plain text. Therefore, if you want to save information such as user names and passwords, you had better encrypt them in advance.

conclusion

Cookies are an older front-end caching technology.

To use it, you have to have a service on the front end (not static web pages), and the storage size is limited to 4KB. So why do you have to have a service to use cookies? Because cookies are sent back and forth between the server and the browser whenever a request is involved. In addition, due to the cross-domain limitation of the browser, the client and server must ensure the principle of the same origin to use, but because cookies are stored in the front end, so the security problem is always a big problem.

Therefore, it is not recommended to store important information in cookies.

localStorage

What is LocalStorage?

In HTML5, a new localStorage feature is added. This feature is mainly used as localStorage, which solves the problem of insufficient cookie storage space (the storage space of each cookie is 4k). The size of localStorage is 5M, which varies with different browsers.

Advantages and limitations of localStorage

advantage

  1. LocalStorage extends the 4K limit for cookies

  2. LocalStorage can store the first request directly locally, which is equivalent to a 5M size database for the front-end page, saving bandwidth compared to cookies, but only supported in older browsers

limited

  1. Browsers have different sizes, and Internet Explorer versions later than Internet Explorer 8 support localStorage

  2. Currently, all browsers limit the value type of localStorage to string, which requires some conversion to the common JSON object type

  3. LocalStorage is not readable under the browser’s privacy mode

  4. LocalStorage is essentially a string read. If you store too much content, memory space will be consumed and pages will become jammed

  5. LocalStorage cannot be retrieved by crawlers

The only difference between localStorage and SessionStorage is that localStorage is a permanent storage, whereas SessionStorage is a key/value pair that is cleared when the session ends

How to use localStorage

LocalStorage is “persistent” — once saved, it stays in the front end without manual cleanup. It is saved as a key-value pair. Here are some ways to use it:

localStorage.length    // Get the number in storage
localStorage.key(n)    // Get the key of the NTH element pair in storage (the first element is 0)
localStorage.getItem(key)    // Get the value of key
localStorage.key    // Get the value of key
localStorage.setItem(key, value)    // Add data with key value and value value
localStorage.removeItem(key)    // Remove key data
localStorage.clear()    // Clear all data
Copy the code

Other precautions for LocalStorage

JSON is normally stored in localStorage, but localStorage automatically converts localStorage to a string.

At this point we can use the json.stringify () method to convert a JSON object into a JSON string

Example:

if(!window.localStorage){
   alert("Browser support localStorage");
}else{
   var storage=window.localStorage;
   var data={
      name:'xiecanyong'.sex:'man'.hobby:'program'
   };
   // Convert a JSON word object into a JSON string input
   var d = JSON.stringify(data);
   storage.setItem("data",d);
   console.log(storage.data);
}
Copy the code

To convert the JSON string to a JSON object after reading it, use the json.parse () method

var storage=window.localStorage;
   var data={
         name:'xiecanyong'.sex:'man'.hobby:'program'
   };
   var d=JSON.stringify(data);
   storage.setItem("data",d);
   // Convert JSON string to JSON object output
   var json=storage.getItem("data");
   var jsonObj=JSON.parse(json);
   console.log(typeof jsonObj);
Copy the code

SessionStorage

What is SessionStorage?

SessionStorage is used to store data in a Session locally. The scope of SessionStorage is window-level, that is, SessionStorage data between different Windows cannot be shared. This data is accessible only to pages in the same session and is destroyed when the session ends. Therefore, SessionStorage is not a persistent local storage, only session level storage.

The characteristics of the SessionStorage

What’s the difference between this and localStorage? As a session-level localStorage, SessionStorage will disappear once you close the browser, whereas localStorage is “persistent”, even if you close the browser 10,000 times, it’s ok, so there’s still a big gap. Front-end engineers like these two front-end caching methods because of the current development model of front – and back-end separation.

SessionStorage

sessionStorage.length    // Get the number in storage
sessionStorage.key(n)    // Get the key of the NTH element pair in storage (the first element is 0)
sessionStorage.getItem(key)    // Get the value of key
sessionStorage.key    // Get the value of key
sessionStorage.setItem(key, value)    // Add data with key value and value value
sessionStorage.removeItem(key)    // Remove key data
sessionStorage.clear()    // Clear all data
Copy the code

indexDB

As the capabilities of the browser continue to increase, more and more sites are considering storing large amounts of data on the client side, which can reduce the amount of data retrieved from the server and bring it directly from the local.

Existing browser data storage schemes are not suitable for storing large amounts of data: cookies are less than 4KB in size, and each request is sent back to the server; LocalStorage is between 2.5MB and 10MB (depending on the browser), does not provide search, and cannot create custom indexes. So a new solution was needed, and this was the context in which IndexedDB was born.

In plain English, an IndexedDB is a browser-provided local database that can be created and manipulated by web scripts. IndexedDB allows you to store large amounts of data, provide a lookup interface, and build indexes. These are all things that LocalStorage does not have. In terms of database type, IndexedDB is not a relational database (it does not support SQL query statements) and is closer to a NoSQL database.

For more information about indexDB, see this article IndexedDB Primer for browser databases

conclusion

The difference between WebStorage, cookie, and IndexedDB

storage cookie localStorge sessionStorge indexDB
The life cycle of data Generally, it is generated by the server. You can set the expiration time Unless it’s cleaned up, it’s always there Clean up when the page is closed Unless it’s cleaned up, it’s always there
Data store size 4M 5M 5M infinite
Communicate with the server Each time carried in the header, the impact on request performance Don’t participate in Don’t participate in Don’t participate in

As you can see from the table above, cookies are no longer recommended for storage. LocalStorage and sessionStorage can be used if you don’t have extensive data storage requirements. For data that does not change much, try to use localStorage, otherwise use sessionStorage.

As a front-end novice, the purpose of this article is to record their learning experience, if there are shortcomings, please also give advice.

The road ahead is long, and I see no end.

Postscript: Hello friends, if you think this article is good, remember to give a thumbs-up or star, your thumbs-up and star is my motivation to write more and richer articles!Making the address



dbThe document library 由 dbusingCreative Commons Attribution – Non-commercial Use – Same way Share 4.0 International LicenseGrant permission.

Based on thegithub.com/danygitgitOn the creation of works.

Use rights other than those authorized by this License agreement may be obtained fromCreativecommons.org/licenses/by…Obtained.