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="//"></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

  • By
    Responsive and Infinitely Scalable JS Animations

    Back in late 2012 it was not easy to find open source projects using requestAnimationFrame() - this is the hook that allows Javascript code to synchronize with a web browser's native paint loop. Animations using this method can run at 60 fps and deliver fantastic...

  • By
    Serving Fonts from CDN

    For maximum performance, we all know we must put our assets on CDN (another domain).  Along with those assets are custom web fonts.  Unfortunately custom web fonts via CDN (or any cross-domain font request) don't work in Firefox or Internet Explorer (correctly so, by spec) though...

Incredible Demos