Using sessionStorage to Conserve Mobile Bandwidth

If you're website also offers a mobile version, it's likely that you are pulling much of your data for the mobile site from your "desktop" site. And, even more likely that you're using AJAX to do it.

However, if you are loading static data repeatedly, you can imagine the unnecessary use of mobile bandwidth can add up to a slower user experience. The HTML 5 spec provides a means to improve this, by storing data in the web browser. This new method provides enhancements over cookies, in that it is safer and easier to access via JavaScript.

Of course, when requesting data via AJAX, there is the option to cache that request in the browser. In the case of jQuery, the cache parameter to the $.ajax method serves this purpose.

However, depending on your server settings, the cache expiration might be a little "strong".

A session type storage is more suitable for a shorter expiration – the life of the user session. HTML 5 supporting browsers offer the sessionStorage and localStorage options along with their respective JavaScript methods. You can leverage sessionStorage by first checking for the existence of a sessionStorage variable, and if it does not exist, perform the appropriate AJAX call to get the data. After which, you would store that data in the sessionStorage scope.

sessionStorage Example

function performAction() {
    if (sessionStorage.myData == null) {
        $.ajax({
            url: 'http://www.mysite.com/getData.cfm',
            dataType: 'jsonp',
            success: function(data) {
                sessionStorage.myData = JSON.stringify(data);
                performActionHelper();
            }
        });
    }
    else
        performActionHelper();
}

function performActionHelper() {
    // processing code here
    console.log(myData);
}

 

There's a couple things to take note of here.

  1. Notice how we separate the processing into another function. This allows us to reuse the code as well as provide a means for the processing code to be executed asynchronously.

    Note: You can't reliably create a function that makes an asynchronous AJAX call, then returns a value, as that value probably won't be available by the time the function returns.
     

  2. sessionStorage currently can only store string data, so we must "flatten" the data, then parse it when needed (see use of JSON.stringify and JSON.parse)

Subscribe

  • follow us in feedly


Tagged .

Updated: 2012-05-05

Phil LaNasa