How to load local script files as fallback in cases where CDN are blocked/unavailable?

raklos picture raklos · Mar 10, 2011 · Viewed 90.8k times · Source

Answer

Dmitry Evseev picture Dmitry Evseev · Apr 3, 2011

To confirm that cdn script loaded you can check for existence any variable/function this script defines, if it is undefined - then cdn failed and you need to load local script copy.

On this principle are based solutions like that:

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="js/libs/jquery-1.5.1.min.js">\x3C/script>')</script>

(if there is no window.jQuery property defined cdn script didn't loaded).

You may build your own solutions using this method. For instance, jquery tooltip plugin creates $.tooltip() function so we can check it with code like this:

<script>
    if (typeof $.tooltip === 'undefined') {
        document.write('<script src="js/libs/jquery.tooltip.min.js">\x3C/script>');
    }
</script>