Search This Blog

Thursday, January 15, 2015

How to Using HTML 5 Local Storage


Loading data from a remote source

When loading data from a remote source I'd use jQuery or Zepto's ajax() function like this:

1$.ajax({
3    dataType: 'JSONp',
4    success: function(data, status) {
5        $.each(data, function(key, value){
6            //handle the data               
7        });
8    },
9    error: function() {
10        //handle the error
11    }
12}

In this example I'm accessing a fictional data source to load a news article.

Once the article is loaded the user might browse another article but later on may return to read this particular one again. You could load the article from your server again. But that's a bit inefficient if you have already loaded it before. You could just as easily store the article locally, using HTML5's localStorage, on the device and request the details from there. That's pretty simple to setup.

HTML5 local and session storage

HTML5 introduced several methods of storing data within the clients browser. Two of these methods are local and session storage. localStorage saves data until it is removed by the client or app whereas sessionStorage saves data until the session ends, when the browser window/tab is closed.

Mark Pilgrim sums up HTML5 local storage as:

a way for web pages to store named key/value pairs locally, within the client web browser. Like cookies, this data persists even after you navigate away from the web site, close your browser tab, exit your browser, or what have you. Unlike cookies, this data is never transmitted to the remote web server (unless you go out of your way to send it manually).

Dive into HTML – Introducing HTML5 local storage

Storing a key/value pair is very straightforward:

1localStorage.setItem('yourKeyName', 'your value');

This works great for simple key/value pairs.

Storing a JSON object in local storage

Attempting to store a JSON object, or an ordinary array of data, in local storage will yield an error. Local storage requires you to store strings of information. To store a JSON object in local storage you will need to convert it into a JSON-formatted string, using the JSON.stringify() function.

Referring back to the ajax example above, we could take the data object and stringify it:

1var dataToStore = JSON.stringify(data);

Then it's just a case of storing the new JSON-formatted string in local storage:

1localStorage.setItem('someData', dataToStore);

Loading a JSON object from local storage

Now that the JSON object is stored locally you can access the data directly from the device, without having to make a request to the remote server. However, because the object was previously converted to a JSON-formatted string, you will have to reverse the effects of the stringify function before you can access the data within the object. This is easily done through use of the JSON.parse() function:

1var localData = JSON.parse(localStorage.getItem('someData'));

Now you can access the object and handle it as you normally would:

1$.each(localData, function(key, value){
2    console.log(key + ' = ' + value);
3});

Using PhoneGap's local storage api

The above example will work in any modern browser as well as in your PhoneGap app, but PhoneGap also provides local storage access via its api:

1//setting an item
2window.localStorage.setItem('key', 'value');
3 
4//loading an item
5var value = window.localStorage.getItem('key');

The only difference here being window. prepended to the ordinary localStorage methods.

Putting it all together in a PhoneGap app

Taking all of this into account you might end up with something like this:

1$.ajax({
3    dataType: 'JSONp',
4    success: function(data, status) {
5        $.each(data, function(key, value){
6            //handle the data               
7        });
8         
9        var localData = JSON.stringify(data);
10         
11        window.localStorage.setItem('newsArticle12', localData);
12    },
13    error: function() {
14        //handle the error
15    }
16}

And when you want to get access to that data the next time:

1var localData = JSON.parse(window.localStorage.getItem('newsArticle12');
2 
3$.each(function(key, value){
4    //handle the data
5});

This is a useful technique to use in PhoneGap apps, it can be a significant optimisation when used appropriately. It reduces server requests and loads your [previously loaded] data faster.

Some considerations

There are some considerations with using local storage though.

There is a limit to how much data you can store via localStorage – approximately 5mb. If you are dealing with a lot of data you could soon reach that limit.

The main consideration should always evaluating the type of data that you are storing locally. Maybe sessionStorage is the better choice if your users require up to date information each time they open your app. Or maybe you need to include an expiry data in your JSON object and check against that before serving the data.

No comments:

Post a Comment