Simple trick to silently fallback when CDN’s unreachable

Nishanth Anil / Wednesday, April 10, 2013

Using content delivery network provides increased performance – since files are copied and replicated, end users accessing content from far off, remote areas do not download content from your web server, but instead from a closer CDN server. Since CDN hosted content is cached; it is a good idea to have JavaScript, Image, and CSS files hosted there as they will be downloaded to the client PC and reused until the client’s browser cache is discarded. This eliminates the bandwidth expense of having to download the same files repeatedly. Google and Microsoft provide their own Ajax Content delivery network which provide JavaScript libraries like jQuery, Knockout, Angular etc..

Since these services come to you free of cost, why wouldn’t you be using it? As a web developer you don’t have to maintain third party JavaScript libraries at all. 

What if they fail?

“Our CDNs are 99.9% uptime guarantee” You would have run into similar statements a number of times with cloud hosting providers. But what if your customer were just unlucky that day(it happens)? Don’t you want to silently fallback to your local servers when that happens? Fortunately there’s a simple trick.

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="../common/jquery-1.8.3.min.js"><\/script>')</script>

Add the above piece of code to your web page, change the CDN URL, update the local path of jQuery, and see the magic happen.

This post has been inspired by HTML5Boilerplate’s implementation of effectively falling back when the jQuery load from a CDN fails.

Don’t forget to check out Infragistics Content Delivery network for Ignite UI 

Have a feedback? Find me on twitter @nishanil