Home  >  Article  >  Web Front-end  >  Web browser-based local storage method application_javascript skills

Web browser-based local storage method application_javascript skills

WBOY
WBOYOriginal
2016-05-16 17:47:531164browse

When storing data on the client, we generally use cookies (insensitive data). However, as clients become increasingly rich, the amount that cookies can store (maximum 4k per domain) is really small.
There is localStorage available in HTML5, but this abandons IE8-. For compatibility, we can dig out a storage method developed by IE a long time ago:
Add a special style url (#default#userData) to an element, and then you can access the key-value pair form through setAttribute and getAttribute. of data.
One thing to note is that you need to use the save method after the data is changed, and you need to load the data in the initial stage.
Next, I will post the usage method. When the browser used supports HTML5, use localStorage.

Copy code The code is as follows:

var localStorage = (function(db) {
if (typeof db.clear == "function") {
return db;
}
var database = document.createElement("div")
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 will be obtained when it is opened through Chrome. Not here.
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn