Use a CDN hosted version of jQuery and fallback to a local copy

Posted in Javascript -

I've always served jQuery off my own websites either as a separate file or included in a combined, minified file with all my other Javascript code. I've moved to using the Google CDN to deliver jQuery instead and include code to fallback to a local copy if the remote one could not be loaded.

Why bother falling back to a local copy?

There may be times when the CDN version cannot be loaded. For example:

  • you're doing development on a disconnected computer
  • a country or workplace network blocks the CDN
  • various connectivity issues

How to load the fallback version if the CDN version cannot be loaded

Add this to your HTML document template:

<script type="text/javascript" src="//"></script>
<script type="text/javascript">
	if(typeof jQuery === 'undefined') {
		document.write(unescape('%3Cscript type="text/javascript" src="/path/to/your/jquery.min.js" %3E%3C/script%3E'));

You would normally put the above in the <head> section, but it can be elsewhere in the document. For example Yahoo's YSlow recommends putting Javascript at the end of the document. Where-ever you put it, it should be before your other Javascript code which relies on jQuery.

This example uses jQuery 1.6.1, which is the current version at the time of writing this post, using the Google CDN. Note the src starts with // and not http:// If you page is hosted on an https:// URL it will use the https:// version of the URL; on http:// it will use the http:// version.

The second <script> section checks to see if jQuery is defined. If it's not, then it writes a script tag into the document to load your local version. Note that loading an external Javascript file is blocking, so this block of code won't execute until either the CDN jQuery file has successfully downloaded, or has failed to download.

The document.write uses an escaped string to avoid issues with the closing </script> tag and uses unescape() to remove this escaping.

Note that I have tested this on IE6, IE7, IE8, Chrome and mobile Safari on the iPhone Simulator both connected and disconnected and the falback works fine in these browsers.

Related posts: