HTML5 Localstorage

I have been recently developing mobile applications using a combination of HTML5, CSS3, Phonegap, and jQuery mobile. This is an amazing stack for developing portable mobile apps without the need to write native applications for each platform. The HTML5 spec, although not finalized is gaining wider and wider adoption and looks to transform mobile application development as well as the traditional web experience.

One of the great features of HTML5 is the ability to store data in the local browswer cache that’s much more robust then that previously afforded by HTTP cookies. There used to be a couple of ways to accomplish this. One was by using the WebSQL concept allowing data storage accessible thorough an SQL type syntax and hierarchal data structures. This method has been deprecated by the W3C (at least for now).

The alternative is HTML5 localstorage which defines access to the local browser cache through a relatively simple API. Localstorage amounts to a map of key value pairs of type string. This is not as limiting as it might at first seem however. There is a very simple way to store javascript objects other than string in the local storage. It’s simply a matter of serializing those objects so that they can be reconstructed for use at a later time.

Here’s a trivial example…

var myObject = {}; = 'Lonnie';
myObject.myFriends = [];
myObject.myFriends[0] = 'Alice';
myObject.myFriends[1] = 'Dave';
myObject.myFriends[2] = 'Mike';

//example of code to store a javascript object as json into local storage
localStorage.setItem(key, JSON.stringify(myObject));

//example of code to restore a javascript object from json out of local storage
var anObject = eval('(' + getLocal().getItem(key) + ')');

You can download a simple working example of this principle here.

In the past, HTTP cookies have been used (some people might say misused) for the purpose of storing more or less persistent browser data. HTML5 local storage provides access to a datastore with much more capacity then that afforded by cookies. Local data caching can allow applications to be much more responsive and even operate in some cases when “offline”, a great capability in the world of mobile applications.