Boldr by N. Merouze

Speed up Ajax with HTML5 Web Storage

I’m beginning a series of articles about the modern features of Web browsers. This article will be about HTML5 Web Storage and particularly localStorage. And because I like it, another twitter example folks!

What is localStorage?

Compatibility of localStorage (as of January 2010) : IE8, Firefox 3.5, Safari 4, Chrome 4, Opera 10.50

Basically it’s like cookies but restricted to the client (the server cannot get data from localStorage), it can store more data (the limit depends of the browser but it’s generally 5MB) and it doesn’t have a time expiration. It’s time for the example!

WARNING: You must test the above example with a real URL (not file://). Otherwise it won’t work in IE and Firefox (but seems to be fine in Safari and Chrome)

The slow way

First we get the tweets and display them. It is slow because each time we access the page the Javascript will request Twitter. And it’s ugly because we have a loading message before displaying the tweets.

To display the tweets instantly we’re gonna store them.

Setter

After each request to Twitter we store the whole JSON response to localStorage. It is just one line:

localStorage.setItem(key, value) take a key for the first argument (“tweets” here) and the value for the second argument (the Twitter JSON response here). WARNING: The value must be a string so if we want to store an object, we stringify it with JSON.stringify(data).

Getter

Then we write the code to get the tweets from localStorage.

To get the data it’s localStorage.getItem(key). If there’s something in it we display them. The first time we access the page there won’t be anything in localStorage so the process will be the same as “The slow way”. The other times the tweets will be displayed instantly. The Twitter request is running too, so it will refresh the list a little bit after the first display in case there’s any new tweets. The rendering will be way prettier than the loading message! You can see the example here.

If we want to clear the localStorage it’s as simple as localStorage.clear().

Old browsers compatibility (progressive enhancement)

If you do that in production, the Javascript will fail for the users who have old browsers. To be safe, we will download Modernizr (I will write an article about Modernizr soon) and check if the browser has a localStorage:

Result

As a result I made a fork of jQuery tweet with localStorage support, so check it out! You won’t see a difference with a server-side rendering.