Let's say I have a name value on the page. The user can change it at any time. The only requirement is that when the user leaves the page and comes back, name should be whatever it was last time.
Would this be a good way to do this?
var nameapp = (function () {
var _name = localStorage.name || "Person";
window.onunload = window.onbeforeunload = function () {
localStorage.name = _name;
};
return {
get: function () {
return _name;
},
set: function (newName) {
_name = newName;
}
};
})();
Questions:
- Is it good practice to manipulate the
localStorageonly when the page is loaded and closed? - It it guaranteed that
onunloadandonbeforeunloadwill fire on all browsers? - Would it be better (or more reliable) to update the value in
localStorageevery time a change occurs?