JavaScript CDN Fallbacks

By  on  

CDNs are great for pulling shared resources from, especially JavaScript libraries. The advantage in the likelihood that a file is already cached before the user gets to our site is huge. The only problem with using a CDN is that it's out of control; more specifically, what if the CDN server is down? What a nightmare! Thousands if not millions of websites would be hurt...but not yours. Nope, you added a CDN fallback so that a failed CDN wouldn't hurt your site!

The HTML / JavaScript

The document.write method is one you generally want to avoid, but it works best in this case:

<!-- Use Google CDN for MooTools, local Moo as a callback -->
<script src="//ajax.googleapis.com/ajax/libs/mootools/1.4.1/mootools-yui-compressed.js"></script>
<script>!window.MooTools && document.write(unescape('%3Cscript src="/js/mootools-yui-compressed.js"%3E%3C/script%3E'))</script>

In the event that the CDN fails, your local file is instead used. Simple but clever fallback, yes? The likelihood that Google or other CDNs is down is small, but since you don't control the other server, there's always that risk! Play it safe!

Recent Features

Incredible Demos