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
    Conquering Impostor Syndrome

    Two years ago I documented my struggles with Imposter Syndrome and the response was immense.  I received messages of support and commiseration from new web developers, veteran engineers, and even persons of all experience levels in other professions.  I've even caught myself reading the post...

  • By
    Being a Dev Dad

    I get asked loads of questions every day but I'm always surprised that they're rarely questions about code or even tech -- many of the questions I get are more about non-dev stuff like what my office is like, what software I use, and oftentimes...

Incredible Demos

  • By
    HTML5 Input Types Alternative

    As you may know, HTML5 has introduced several new input types: number, date, color, range, etc. The question is: should you start using these controls or not? As much as I want to say "Yes", I think they are not yet ready for any real life...

  • By
    Editable Content Using MooTools 1.2, PHP, and MySQL

    Everybody and their aerobics instructor wants to be able to edit their own website these days. And why wouldn't they? I mean, they have a $500 budget, no HTML/CSS experience, and extraordinary expectations. Enough ranting though. Having a website that allows for...