HTML5 Series - Web Storage

One of the best benefits of HTML5 particularly for Web Apps is the ability to store data locally within the users browser. This means in many places you can speed your Web App up by fetching data once and then retrieving it locally in the future, rather than going back to a server each time.

There are 2 types of storage available localStorage and sessionStorage. The simple difference is that localStorage doesn't expire while sessionStorage expires at the end of the users session.

Both types store data in a key/value list and could not be simpler:

// local storage
localStorage.variableName = value;

// session storage
sessionStorage.variableName = value;

One thing to note though is you can only store text. If you want to store something more complex the simple solution is to convert it to and from JSON. E.g.

var myColours = [ 'red', 'blue', 'green', 'yellow'];

// Save to local storage
localStorage.colours = JSON.stringify(myColours)

// Retrieve from local storage
var retrievedColorus = JSON.parse(localStorage.colours);