In my last article I described how to improve the speed of your Rails 3 Ajax Application by returning correct HTTP states and optimizing browser caching.
One thing that still annoyed me was the fact that the browser had to wait for the 304 “Not Modified” response from the server before displaying cached data. Once the response was received it would trigger the success callback. That means the user needs to wait for a response from the server just so that the browser can display cached data…
At that point I remembered reading about Wycats’ jquery-offline. jQuery-Offline has the same interface as jQuery’s native getJSON, but once it receives the response it’ll store the JSON data in the browser’s localStorage. The next time the same Ajax request is triggered the success callback is executed twice. First when the data is loaded from the localStorage (which is very very fast obviously) and the second time when the browser returns a 200 status response. The great thing is, that the success callback won’t be triggered if the server returns a 304 “Not Modified” status code. This is really really neat and makes the UI unbelievably snappy.
jQuery.retrieveJSON( "/lists/1", { options: "in case you need it" }, function( data, textStatus, jqXhr) { // process the data. This will be called up to two times. } );
Unfortunately getJSON doesn’t have a great way to handle errors. Since retrieveJSON uses the same interface it suffers from the same weakness. Luckily jQuery 1.5 introduced the jqXHR object. With jqXHR error handling becomes real easy:
var jqXhr = jQuery.retrieveJSON( "/lists/1", { options: "in case you need it" }, function( data, textStatus, jqXhr) { // process the data. This will be called up to two times. } ); jqXhr.error( function( xhr, errorType, exception ) { // do your error handling here. } );
If you want to use above functionality you need to use my fork of jQuery-Offline because the official version hasn’t been updated yet to return a jqXhr object.

I'm a Software Developer, currently working at