First recognized the local storage of html5 localStorage, html5localstorage

Source: Internet
Author: User
Tags website performance hasownproperty sessionstorage

First recognized the local storage of html5 localStorage, html5localstorage

I. Overview

HTML5 provides two new methods to store data on the client:

  • LocalStorage-data storage with no time limit
  • SessionStorage-data storage for a session

Previously, these are all completed by cookies. However, cookies are not suitable for storing a large amount of data because they are transmitted by each request to the server, which makes the cookie speed slow and inefficient.

In HTML5, data is transmitted not by each server request, but only by the request. It makes it possible to store a large amount of data without affecting the website performance.

For different websites, data is stored in different regions, and a website can only access its own data.

HTML5 uses JavaScript to store and access data.

/*********************** From w3c ************* ***************/

Ii. Usage Summary

(1) set the value

1. localStorage. setItem (key, value): If the key value exists, update the key value, for example, localStorage. setItem ("name", "moomoo"); [Recommended syntax]

2. localStorage. name = "moomoo ";

3. localStorage ["name"] = "moomoo ";

(2) obtain the value

1. localStorage. getItem (key, value): If the key value does not exist, null is returned, for example: localStorage. getItem ("name"); [Recommended syntax]

2. var name = localStorage. name;

3. var name = localStorage ["name"];

(3) clear values

1. localStorage. remove (key) indicates clearing the value of a single key, for example, localStorage. remove ("name"). executing this statement will clear the value of name.

2. localStorage. clear () indicates clearing all data stored in localStorage

(4) traverse stored data

When you do not know how much data is stored in local localStorage, using the key (index) method is definitely a good choice. The key (index) method can traverse the keys stored in localStorage. Write a simple example:

For (I = 0; I <localStorage. length; I ++ ){

Document. write (localStorage. key (I) + ":" + localStorage. getItem (localStorage. key (I) + "<br/> ");

}

LocalStorage. length indicates the total amount of data stored locally;

LocalStorage. key (I) indicates the key to obtain the I data;

LocalStorage. getItem (localStorage. key (I) indicates to obtain the value of the I data.

(5) JSON Storage

When you need to store a large amount of data, you can store the data in arrays and convert the data into JSON format.

1. JSON. stringify (data) converts an object into a JSON data string.

2. JSON. parse (data) parses the data into an object and returns the parsed object.

In this case, it may not be easy to understand. The following is an example:

Var arr = {"name": "moomoo", "age": 2, "eat": "apple "};

LocalStorage. setItem ("arr", JSON. stringify (arr ));

Arr = JSON. parse (localStorage. getItem ("arr "));

If you want to determine whether the information is actually stored locally in the browser, use Google as an example: Right-click the blank area of the browser and choose check (directly done)

In this way, you can easily review the data stored locally.

Note that the data stored in localStorage cannot be shared across browsers. That is to say, the data stored in the browser can only be accessed in this browser. Currently, the storage space of each browser is 5 MB.

(6) sessionStorage

SessionStorage is a global object that maintains a valid storage space during a page session. As long as the browser is open, the page session cycle will continue. When the page is reloaded or restored, the page session also exists. Each time a new page is opened in a new tag or window, a new session is initialized, that is, sessionStorage stores data for a session. When the user closes the browser window, the data will be deleted.

When the browser is accidentally refreshed, some temporary data should be saved and restored. SessionStorage objects are most useful when dealing with such situations. SessionStorage automatically saves the content in a text field. If the browser is accidentally refreshed, the content in the text field will be restored, so no input data will be lost.

The sessionStorage method is similar to the localStorage method.

(7) Compatibility

Not all browsers support this function. If you want to use it in a browser without native support for localStorage objects, you can insert any of the following two sections of code in the header of your JavaScript code.

if (!window.localStorage) {  Object.defineProperty(window, "localStorage", new (function () {    var aKeys = [], oStorage = {};    Object.defineProperty(oStorage, "getItem", {      value: function (sKey) { return sKey ? this[sKey] : null; },      writable: false,      configurable: false,      enumerable: false    });    Object.defineProperty(oStorage, "key", {      value: function (nKeyId) { return aKeys[nKeyId]; },      writable: false,      configurable: false,      enumerable: false    });    Object.defineProperty(oStorage, "setItem", {      value: function (sKey, sValue) {        if(!sKey) { return; }        document.cookie = escape(sKey) + "=" + escape(sValue) + "; path=/";      },      writable: false,      configurable: false,      enumerable: false    });    Object.defineProperty(oStorage, "length", {      get: function () { return aKeys.length; },      configurable: false,      enumerable: false    });    Object.defineProperty(oStorage, "removeItem", {      value: function (sKey) {        if(!sKey) { return; }        var sExpDate = new Date();        sExpDate.setDate(sExpDate.getDate() - 1);        document.cookie = escape(sKey) + "=; expires=" + sExpDate.toGMTString() + "; path=/";      },      writable: false,      configurable: false,      enumerable: false    });    this.get = function () {      var iThisIndx;      for (var sKey in oStorage) {        iThisIndx = aKeys.indexOf(sKey);        if (iThisIndx === -1) { oStorage.setItem(sKey, oStorage[sKey]); }        else { aKeys.splice(iThisIndx, 1); }        delete oStorage[sKey];      }      for (aKeys; aKeys.length > 0; aKeys.splice(0, 1)) { oStorage.removeItem(aKeys[0]); }      for (var iCouple, iKey, iCouplId = 0, aCouples = document.cookie.split(/\s*;\s*/); iCouplId < aCouples.length; iCouplId++) {        iCouple = aCouples[iCouplId].split(/\s*=\s*/);        if (iCouple.length > 1) {          oStorage[iKey = unescape(iCouple[0])] = unescape(iCouple[1]);          aKeys.push(iKey);        }      }      return oStorage;    };    this.configurable = false;    this.enumerable = true;  })());}

Or

if (!window.localStorage) {  window.localStorage = {    getItem: function (sKey) {      if (!sKey || !this.hasOwnProperty(sKey)) { return null; }      return unescape(document.cookie.replace(new RegExp("(?:^|.*;\\s*)" + escape(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=\\s*((?:[^;](?!;))*[^;]?).*"), "$1"));    },    key: function (nKeyId) { return unescape(document.cookie.replace(/\s*\=(?:.(?!;))*$/, "").split(/\s*\=(?:[^;](?!;))*[^;]?;\s*/)[nKeyId]); },    setItem: function (sKey, sValue) {      if(!sKey) { return; }      document.cookie = escape(sKey) + "=" + escape(sValue) + "; path=/";      this.length = document.cookie.match(/\=/g).length;    },    length: 0,    removeItem: function (sKey) {      if (!sKey || !this.hasOwnProperty(sKey)) { return; }      var sExpDate = new Date();      sExpDate.setDate(sExpDate.getDate() - 1);      document.cookie = escape(sKey) + "=; expires=" + sExpDate.toGMTString() + "; path=/";      this.length--;    },    hasOwnProperty: function (sKey) { return (new RegExp("(?:^|;\\s*)" + escape(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=")).test(document.cookie); }  };  window.localStorage.length = (document.cookie.match(/\=/g) || window.localStorage).length;}

Everyone understands it on their own ...... These two paragraphs ...... Does not understand/(ㄒ o knowledge )/~~

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.