Categories
Web Development

localStorage With Cookie Fallback

I mentioned the other day that localStorage can be used as an alternative for cookies. The benefit is that localStorage doesn’t sent it’s data back on every request to the server like a cookie. Headers are uncompressed in http making that very costly. However not every web browser out there supports localStorage. Most however do.

Here’s an example based on jQuery and jQuery.cookie. It’s designed to turn objects into JSON and store the JSON representation. On retrieval it restores the object. This doesn’t handle things like expiring cookies (it simply defaults to 365 days). I just had this around from an old project with these very specific requirements and figured I’d post it as-is in case it can help anyone and to demonstrate. This isn’t ideal for reuse, but for someone playing with the idea, maybe it will motivate 😉 .

function storeData(type, obj){
    var data = jQuery.toJSON(obj);
 
    // If using a modern browser, lets use localStorage and avoid the overhead
    // of a cookie
    if(typeof localStorage != ‘undefined’ && localStorage !== null){
        localStorage[type] = data;
    }
 
    // Otherwise we need to store data in a cookie, not quite so eloquent.
    else {
        jQuery.cookie(type, data, { expires: 365, path: ‘/’ });
    }
}
 
function loadStoredData(type){
     var data;
 
    // If using localStorage, retrieve from there
    if(typeof localStorage != ‘undefined’ && localStorage !== null){
        data = localStorage[type];
    }
 
    // Otherwise we have to use cookie based storage
    else {
        data = jQuery.cookie(type);
    }
 
    // If we have data, lets turn it into an object, otherwise return false
    if(data){
        return jQuery.secureEvalJSON(data);
    }
    return false;
}

Pretty simple right? It’s still a key/value API.

2 replies on “localStorage With Cookie Fallback”

Cool… doesn’t look to me like it deserializes JSON. Normally I’d typeof to handle that, but this post is what I used on safepasswd.com to “remember” your last settings. In that use case, it’s always an object hence unnecessary.

Leave a Reply

Your email address will not be published. Required fields are marked *