Thursday, February 19, 2009

How do I automatically revert to local javascript when offline?

I work on Rails applications that include jquery javascript files from ajax.googleapis.com. Every now and then I have to work on those apps offline.
e.g. when I commute on trains.

The application has the same jquery javascript files locally so the old way of working offline was to comment out the google jquery include calls and uncomment the local javascript include calls.

I decided I didn't want to have to bother with that so I implemented something that will check if I am connected online or not and make the appropriate javascript include calls.

The code looks like this:
- if Ping.pingecho("ajax.googleapis.com", 10, 80)
  = google_jquery
- else
  = javascript_include_tag 'jquery-1.2.6.min.js'


The added bonus is that if ever ajax.googleapis.com goes down then our apps won't be affected.

p.s. the above code is markup in haml and uses google_ajax_libraries_api plugin and ping.rb which comes with standard ruby installation. Down the track I might modify the plugin to support the offline backup.