JQuery CDN with fallback strategy

Smart usage of CDN for JQuery and JQuery plugins

  • Share

Content Delivery Network or CDN is really usefull for loading JQuery and especially JQuery UI since it is pretty big script file. They are very ofter reliable, fast and since they can be used on other sites, they might be alrady cached in clients browser if he visited some website which uses the same CDN for JQuery or JQuery UI.

There are a lot of CDN providers outhere, but two most common are for sure:

As I said, they are available most of the time, but it might happend that they are not accessible for many reasons. In that case, it would be really nice if you could just load your server local copy of JavaScript library.

This is possible with very few lines of JavaScript code.

<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/jquery-ui.min.js"></script>

<script type="text/javascript">
    if (typeof jQuery == 'undefined') {
        document.write(unescape("%3Cscript src='/Scripts/jquery-1.11.0.min.js' type='text/javascript'%3E%3C/script%3E"));
    }
    if (typeof jQuery.ui !== 'undefined') {
        document.write(unescape("%3Cscript src='/Scripts/jquery-ui-1.10.4.min.js' type='text/javascript'%3E%3C/script%3E"));
    }
</script>
    

This code will dynamically add script tags pointing to local server copies of JavaSCript libraries in case they are failed to load from CDN. This way you are protected in case some of CDN-s you are using is temporary down.

Problem with these two is that they are hosting only most popular JavaSCript libraries and very often you need to use some not so popular librarries for your website. There are a lot of CDNs which host big number of not so poular JavaScript libraries. These are some of thouse you can use to reference your script sources:

References

  • Share

Disclaimer

Purpose of the code contained in snippets or available for download in this article is solely for learning and demo purposes. Author will not be held responsible for any failure or damages caused due to any other usage.

Comments for this article

comments powered by Disqus