How and Why: CDN Hosted jQuery with a Local Fall-Back Copy
Posted by in jQueryAs explained here, there are several good reasons for using CDN hosted jQuery. But what about the downside?
Really, there isn’t much of one. The primary argument against using hosted CDN hosted jQuery is that the CDN might suffer an outage. Now granted, that’s very unlikely to happen with the likes of Google, Microsoft and jQuery.com, but it is possible nonetheless. If your site absolutely must have jQuery loaded and available at all times, having the essential files hosted elsewhere is a risk you might not be willing to take.
But never fear, there is a solution: You can have CDN hosted jQuery as your Plan A, and fall back to a local copy as your Plan B.
Here’s how
First, load in your CDN hosted jQuery file as normal. The example below uses the Google CDN (more detail here). See instructions for Microsoft’s CDN and the jQuery.com CDN.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js" type="text/javascript"></script>
Next, right below that, in the <head> of your document, you should add the following JavaScript…
<script type="text/javascript">
if (typeof jQuery === 'undefined') {
var e = document.createElement('script');
e.src = '/local/jquery-1.6.1.min.js';
e.type='text/javascript';
document.getElementsByTagName("head")[0].appendChild(e);
}
</script>
After that, you can go ahead and add whatever other JavaScript you like.
A word of caution
Note that the above is a very basic fall-back method, and it has some limitations. For example, while the fall-back procedure is in process, your other JavaScript files with jQuery dependencies will go ahead and load regardless, no waiting. This may cause problems.
For more advanced and robust solutions, check out this post on happyworm.com.
