How to load local static files if CDN fails without using document.write()?
You should listen to the onerror event, if it occurs then load the local one.
Here is an example (you should change the code to fit your case):
<script>
function onJqueryLoadError()
{
document.write('<scr' + 'ipt src="static/jquery-3.4.1.min.js"></scr' + 'ipt>');
}
</script>
<script src="https://www.cdn/jquery-3.4.1.min.js" onerror="onJqueryLoadError()"></script>
CDNs fail, but your scripts don't have to - fallback from CDN to local jQuery
Falling back from CDN to local copies of jQuery and JavaScript
The basic idea for CDN fallback is to check for a type or variable that should be present after a script load, and if it's not there, try getting that script locally. Note the important escape characters within the document.write. Here's jQuery:
<script src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-2.0.0.min.js"></script> <script> if (typeof jQuery == 'undefined') { document.write(unescape("%3Cscript src='/js/jquery-2.0.0.min.js' type='text/javascript'%3E%3C/script%3E")); } </script>
Or, slightly differently. This example uses protocol-less URLS, checks a different way and escapes the document.write differently.
<script src="//ajax.aspnetcdn.com/ajax/jquery/jquery-2.0.0.min.js"></script> <script>window.jQuery || document.write('<script src="js/jquery-2.0.0.min.js">x3C/script>')</script>
If you are loading other plugins you'll want to check for other things like the presence of specific functions added by your 3rd party library, as in "if (type of $.foo)" for jQuery plugins.
Some folks use a JavaScript loader like yepnope. In this example you check for jQuery as the complete (loading) event fires:
yepnope([{ load: 'http://ajax.aspnetcdn.com/ajax/jquery/jquery-2.0.0.min.js', complete: function () { if (!window.jQuery) { yepnope('js/jquery-2.0.0.min.js'); } } }]);
Even better, RequireJS has a really cool shorthand for fallback URLs which makes me smile:
requirejs.config({ enforceDefine: true, paths: { jquery: [ '//ajax.aspnetcdn.com/ajax/jquery/jquery-2.0.0.min', //If the CDN location fails, load from this location 'js/jquery-2.0.0.min' ] } }); //Later require(['jquery'], function ($) { });
With RequireJS you can then setup dependencies between modules as well and it will take care of the details. Also check out this video on Using Require.JS in an ASP.NET MVC application with Jonathan Creamer.
Updated ASP.NET Web Forms 4.5 falls back from CDN automatically
For ASP.NET Web Forms developers, I'll bet you didn't know this little gem. Here's another good reason to move your ASP.NET sites to ASP.NET 4.5 - using a CDN and falling back to local files is built into the framework.