It’s been a while since the last post, but here were go again anyway! Today there was a small problem with OpenDNS whereby anyone using their service would find that Google’s content delivery network was blocked as a phishing site.

Oh well you say, but Google’s CDN hosts jQuery and have a look at how many sites use this hosted version….

Needless to say I found myself in the situation this morning where a lot of my websites appeared to have failed, along with a large portion of the web. Once DNS settings were changed however things got back to normal. This got me thinking though, that if the CDN does actually go down for real my sites will need a redundant fallback.

This is to say that a local version of jQuery can be stored on the server for the site to use if it detects that the requested CDN version can not be found

With a slight Joomla tailoring, to do this you need to:

  1. Download a version of jQuery. (from jquery.com or similar)

  2. Create a directory on your site called js. I placed mine in /templates/js

  3. Put the downloaded jQuery file in this directory.

  4. Create a second file in this directory called loader.js

  5. Within this file, put the following content:

if (typeof jQuery == 'undefined') {
    document.write(unescape("%3Cscript src='templates/js/jquery.1.6.4.min.js'; ?>' type='text/javascript'%3E%3C/script%3E"));
}

This will check if jQuery has been loaded and if not add a script tag to the current page to load the fallback jQuery file.

In every file you have called the CDN jQuery we need to include our loader.js. It is important to include this file after the CDN call but before any other javascript (inline or loading of other libraries/plugins). The result would look something like this:

$document = JFactory::getDocument();

$document->addScript('http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js');

$document->addScript(JURI::root() . 'templates/js/loader.js');

//Other includes can go here
This should be a bulletproof system that will ensure your sites don’t horribly break should a hosted version of jQuery let you down.