1

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 localStorage only when the page is loaded and closed?
  • It it guaranteed that onunload and onbeforeunload will fire on all browsers?
  • Would it be better (or more reliable) to update the value in localStorage every time a change occurs?
dodov
  • 5,206
  • 3
  • 34
  • 65
  • Well, depends mostly on your app. How often do you have to change the name? If its once every second or more, doubt your performance would hurt by updating directly on localstorage just a short string value – juvian Feb 15 '17 at 17:25
  • I just want the browser to remember a value while keeping the use of localStorage minimal. The reason is because it could be disabled or non-existent and I don't want to make `if (storageEnabled)` checks all the time. I need a variable that is initialized to whatever its state was when the user was on the page last time. – dodov Feb 15 '17 at 17:35
  • could only find these related questions : http://stackoverflow.com/questions/13671613/local-storage-on-window-unload-event and http://stackoverflow.com/questions/24324365/save-before-unload – juvian Feb 15 '17 at 17:46

0 Answers0