Two tips for localStorage

I will keep this short and I hope this will help you avoid some of the headaches localStorage has given me.

1. false is iffy. Use null.

localStorage saves everything as string, so false gets saved as the string "false" which, when loaded back from localStorage, evaluates to true. Use null as that will eval to false, or build a special parser.

2. Writing to localStorage is expensive!

In some cases, it can take out any smoothness your user experience had. Whenever you assign a value to a localStorage key, the browser takes some time for IO -- and that freezes it for a little bit. Try to group writes and make sure you write only when you need to.

Consider this example, and check the profiling screenshot:

$.window = $(window);

function save_position(){
    localStorage.y = $.window.scrollTop();
}

$.window.scroll(function(){
    $('body script');
    save_position();
});

Localstorage

Saving to localStorage takes up most CPU time! Not only does it do that, but it also blocks up the scrolling and it I feel like I'm back in '99.

Now here's an optimized version:

var write_timeout = null;
$.window = $(window);

function save_position(){
    localStorage.y = $.window.scrollTop();
}

$.window.scroll(function(){
    write_timeout && clearTimeout(write_timeout);
    $('body script');
    write_timeout = setTimeout(save_position, 500);
});

This yields the folloing profile:

Localstorage_improved

I think this logic applies to when ever you have to save information during user interaction: use a throttle cap. In this case, a setTimeout.

Viewed  // 
times