A Simple and Robust jQuery 1.4 CDN Failover in One Line

Thursday, January 28th, 2010

Mark Boas

Google, Yahoo, Microsoft and others host a variety of JavaScript libraries on their Content Delivery Networks (CDN) – the most popular of these libraries being jQuery. But it’s not until the release of jQuery 1.4 that we were able to create a robust failover solution should the CDN not be available.

First off, lets look into why you might want to use a CDN for your JavaScript libraries:

1. Caching – The chances are the person already has the resource cached from another website that linked to it.

2. Reduced Latency – For the vast majority the CDN is very likely to be much faster and closer than your own server.

3. Parallelism – There is a limit to the number of simultaneously connections you can make to the same server. By offloading resource to the CDN you free up a connection.

4. Cleanliness – Serving your static content from another domain can help ensure that you don’t get unnecessary cookies coming back with the request.

All these aspects are likely to add up to better performance for your website – something we should all be striving for.

For more discussion of this issue I highly recommend this article from Billy Hoffman : Should You Use JavaScript Library CDNs? which includes arguments for and against.

The fly in the ointment is that we are introducing another point of failure.

Major CDNs do occasionally experience outages and when that happens this means that potentially all the sites relying on that CDN go down too. So far this has happened fairly infrequently but it is always good practice to keep your points of failure to a minimum or at least provide a failover. A failover being a backup method you use if your primary method fails.

I started looking at a failover solution for loading jQuery1.3.2 from a CDN some months ago. Unfortunately jQuery 1.3.2 doesn’t recognise that the DOM is ready if it is added to a page AFTER the page has loaded. This made making a simple but robust JavaScript failover solution more difficult as the possibility existed for a race condition to occur with jQuery loading after the page is ready. Alternative methods that relied on blocking the page load and retrying an alternative source if the primary returned a 404 (page not found) error code were complicated by the fact that the Opera browser didn’t fire the "load" event in this situation, so when creating a cross-browser solution it was difficult to move on to the backup resource.

In short, writing a robust failover solution wasn’t easy and would consume significant resource. It was doubtful that the benefit would justify the expense.

The good news is that jQuery1.4 now checks for the dom-ready state and doesn’t just rely on the dom-ready event to detect when the DOM is ready, meaning that we can now use a simpler solution with more confidence.

Note that importantly the dom-ready state is now implemented in Firefox 3.6, bringing it in line with Chrome, Safari, Opera and Internet Explorer. This then gives us great browser coverage.

So now in order to provide an acceptably robust failover solution all you need do is include your link to the CDN hosted version of jQuery as usual :

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>

and add some JS inline, similar to this:

  <script type="text/javascript">
  if (typeof jQuery === 'undefined') {
     var e = document.createElement('script');
     e.src = '/local/jquery-1.4.min.js';

You are then free to load your own JavaScript as usual:

<script type="text/javascript" src="my.js"></script>

It should be well noted however that the above approach does not "defer" execution of other script loading (such as jQuery plugins) or script-execution (such as inline JavaScript) until after jQuery has fully loaded. Because the fallbacks rely on appending script tags, further script tags after it in the markup would load/execute immediately and not wait for the local jQuery to load, which could cause dependency errors.

One such solution is:

<script type="text/javascript">
  if (typeof jQuery === 'undefined') 
     document.write('script type="text/javascript" src="/local/jquery-1.4.min.js"><\/script>');

Not quite as neat perhaps, but crucially if you use a document.write() you will block other JavaScript included lower in the page from loading and executing.

Alternatively you can use Getify‘s excellent JavaScript Loading and Blocking library LABjs to create a more solid solution, something like this :

  <script type="text/javascript" src="LAB.js">
  <script type="text/javascript">
  function loadDependencies(){

  if (typeof window.jQuery === "undefined") 
     // first load failed, load local fallback, then dependencies
     // first load was a success, proceed to loading dependencies.     

Note that since the dom-ready state is only available in Firefox 3.6 + <script> only solutions without something like LABjs are still not guaranteed to work well with versions of Firefox 3.5 and below and even with LABjs only with jQuery 1.4 (and above).

This is because LABjs contains a patch to add the missing "document.readyState" to those older Firefox browsers, so that when jQuery comes in, it sees the property with the correct value and dom-ready works as expected.

If you don’t want to use LABjs you could implement a similar patch like so:

  <script type="text/javascript">
     if (d[r] == null && d[addEvent]){
        d[r] = "loading";
        d[addEvent](domLoaded,handler = function(){
        d[r] = c;

(Adapted from a hack suggested by Andrea Giammarchi.)

So far we have talked about CDN failure but what happens if the CDN is simply taking a long time to respond? The page-load will be delayed for that whole time before proceeding. To avoid this situation some sort of time based solution is required.

Using LABjs, you could construct a (somewhat more elaborate) solution that would also deal with the timeout issue:

  <script type="text/javascript" src="LAB.js"></script>

  <script type="text/javascript">
  function test_jQuery() { jQuery(""); }
  function success_jQuery() { alert("jQuery is loaded!"); 

  var successfully_loaded = false;
  function loadOrFallback(scripts,idx) {
     function testAndFallback() {
        if (successfully_loaded) return; // already loaded successfully, so just bail
        try {
           successfully_loaded = true; // won't execute if the previous "test" fails
        } catch(err) {
           if (idx < scripts.length-1) loadOrFallback(scripts,idx+1);
     if (idx == null) idx = 0;
     var fallback_timeout = setTimeout(testAndFallback,10*1000); // only wait 10 seconds
     {src:"http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js", test:test_jQuery, success:success_jQuery),
     {src:"/local/jquery-1.4.min.js", test:test_jQuery, success:success_jQuery}

To sum up – creating a truly robust failover solution is not simple. We need to consider browser incompatabilities, document states and events, dependencies, deferred loading and time-outs! Thankfully tools like LABjs exist to help us ease the pain by giving us complete control over the loading of our JavaScript files. Having said that, you may find that in many cases the <script> only solutions may be good enough for your needs.

Either way my hope is that these methods and techniques provide you with the means to implement a robust and efficient failover mechanism in very few bytes.

A big thanks to Kyle Simpson, John Resig, Phil Dokas, Aaoran Saray and Andrea Giammarchi for the inspiration and information for this post.

Mark B

Related articles / resources:








Tags: , , ,

Thursday, January 28th, 2010 AJAX, configuration, development, javascript, jQuery

10 Comments to A Simple and Robust jQuery 1.4 CDN Failover in One Line

  • I’ve been working this week on an extension to LABjs to directly support CDN failover in the LABjs chain, without needing complicated extra steps. The alt parameter specifies the alternate URL (or, optionally, another object with full settings). The test parameter specifies either the name of a property to test for on window (i.e. “jQuery”), a property chain from window to test for (i.e. “jQuery.ui”), or a function that returns true if the load was successful. The timeout used is also customizable using the CDNWaitTime option in setOptions.

    Currently, it’s in testing, but I’d love feedback.

    Git: http://github.com/btburnett3/LABjs
    Test: http://btburnett.com/LABjs

    Here’s an example chain:

    .script({src: “http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js”, alt: “/local/jquery-1.4.min.js”, test: “jQuery”})
    .wait(function() { alert(“Loaded!”); });

  • MarkB says:

    That sounds ideal. I’ll certainly take a look! :)

  • Dude, nice article. If I am not wrong, LAB JS already implements my suggestion to avoid the readyState failure problem, I wrote about it in the jQuery ML and in WebReflection after.
    Thanks to mention it in any case. Regards

  • MarkB says:

    Andrea – you are right! I mention it in case you want to implement it without LABjs. Great work by the way!

  • Steven Black says:

    Hi Mark!

    I posed the original question on the jQuery board and, I must say, you’ve really nailed it. Great article!

    BTW, have you seen this article? http://zoompf.com/blog/2010/01/should-you-use-javascript-library-cdns/ As a result, I’ve been re-evaluating the whole CDN thing…

    **–** Steve

  • [...] what if I want to use LABjs in a larger solution for creating robust fallback for resource loading from CDN locations? I need to conditionally decide during loading/run-time if I need to add more scripts to the [...]

  • [...] For more advanced and robust solutions, check out this post on happyworm.com. [...]

  • [...] co robić jak wersja ta jest niedostępna – np. strona CDN padła? Zrób to (miękki upadek – [...]

  • Developer says:

    Why is there 3 equal signs?

    if (typeof jQuery === ‘undefined’)

  • asian says:

    document.write(‘script type=”text/javascript” src=”/local/jquery-1.4.min.js”>’);