Web browser-based local storage method _ javascript tips-js tutorial

Source: Internet
Author: User
When the client stores data, we generally use cookies (non-sensitive data). However, as the client becomes increasingly rich, the amount of cookies that can be stored (up to 4 k per domain) is small, we cannot meet our requirements. When the client stores data, we usually use cookies (non-sensitive data). However, as the client becomes increasingly rich today, the amount of cookies that can be stored (up to 4 k per domain) is really small.
LocalStorage is available in HTML5, but IE8-is discarded -. To ensure compatibility, we can find a storage method that I used a long time ago:
Add a special style url (# default # userData) to an element, and then you can use setAttribute and getAttribute to access data in the form of key-value pairs.
Note that the save method should be used after the data changes, and load should be used at the initial stage of data loading.
Next, paste the usage method. When the browser used supports HTML5, use localStorage.

The Code is as follows:


Var localStorage = (function (db ){
If (typeof db. clear = "function "){
Return db;
}
Var database = document. createElement ("p ")
Database. id = "database ";
Database. style. behavior = "url (# default # userData )";
Document. body. appendChild (database );
Database. load ("DataStore ");
Return {
SetItem: function (key, val ){
Database. setAttribute (key, val );
Database. save ("DataStore ");
}
, GetItem: function (key ){
Return database. getAttribute (key );
}
, RemoveItem: function (key ){
Database. removeAttribute (key );
Database. save ("DataStore ");
}
};
} (LocalStorage || {}));


However, even if it is compatible, there will still be problems. For example, the information stored on IE cannot be obtained when it is opened through Chrome.

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.