External dependencies are, in fact, external. As such, they are calculated risks with tradeoffs. CDNs are great, but for those minutes or hours that they go down a year, they can be very annoying.
How can we as application developers fallback gracefully when an external dependency like a CDN goes down?
With JavaScript we can detect when our CDN-hosted JavaScript resources like jQuery or jQuery UI aren't loaded successfully and try again to load them from local locations.
One way to create a CDN fallback is to check for a type or variable that should be present after a script load. If that variable is not there, try getting that script locally.
Note the important escape characters within the document.write. Here's a jQuery example:
2<script>
3if (typeof jQuery == 'undefined') {
4 document.write(unescape("%3Cscript src='/js/jquery-2.0.0.min.js' type='text/javascript'%3E%3C/script%3E"));
5}
6</script>
Or you can do something like this:
2<script>window.jQuery || document.write('<script src="js/jquery-2.0.0.min.js">\x3C/script>')</script>
You can also use RequireJS, which has a great shorthand for fallback URLs:
2 enforceDefine: true,
3 paths: {
4 jquery: [
5 '//ajax.aspnetcdn.com/ajax/jquery/jquery-2.0.0.min',
6 //If the CDN location fails, load from this location
7 'js/jquery-2.0.0.min'
8 ]
9 }
10});
11
12//Later
13require(['jquery'], function ($) {
14});
As always, plan for the worst and hope for the best!
Team Ravenglass