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

  • By
    CSS @supports

    Feature detection via JavaScript is a client side best practice and for all the right reasons, but unfortunately that same functionality hasn't been available within CSS.  What we end up doing is repeating the same properties multiple times with each browser prefix.  Yuck.  Another thing we...

  • By
    Detect DOM Node Insertions with JavaScript and CSS Animations

    I work with an awesome cast of developers at Mozilla, and one of them in Daniel Buchner. Daniel's shared with me an awesome strategy for detecting when nodes have been injected into a parent node without using the deprecated DOM Events API.

Incredible Demos

  • By
    Web Audio API

    The Web Audio API allows developers to load and decode audio on demand using JavaScript.  The more I evaluate awesome games for Firefox OS TVs, the more I get to learn about these APIs that I normally wouldn't touch.  The following is a very basic introduction to the WebAudio API...

  • By
    CSS Kwicks

    One of the effects that made me excited about client side and JavaScript was the Kwicks effect.  Take a list of items and react to them accordingly when hovered.  Simple, sweet.  The effect was originally created with JavaScript but come five years later, our...