Karolo Design

Digital Design & Branding

CDN Fail - A bulletproof approach to loading your Javascript Library

CDN Fail - A bulletproof approach to loading your Javascript Library

If you haven't read it yet, our last article looked at how, by loading a Javascript library like JQuery, Prototype or Mootools from a Content Delivery Network, you could shave some time off page load times on your website. You should read that article. This one explains the possible downsides of using CDNs, and how you can protect yourself against them.

So, calling your Javascript libraries from a CDN where possible, is good. But what if that CDN goes down, or is for some reason inaccessible? Admittedly, this isn't likely, but you will find that some people have limited access to the net. Some countries, for example, have limited access to the internet as a whole, and some have chosen to blacklist certain large corporations, so maybe your users won’t be able to access CDN files, even if (as is almost certain) the CDN is in great shape.

So, what can you do?

You can fallback load the library you want. Basically, you need to establish whether the library loaded, by trying to access an object it establishes, and then load a different script if that fails. Try this for size:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
    if (typeof jQuery == "undefined") {
        document.write(unescape("%3Cscript src='/path/to/your/jquery' type='text/javascript'%3E%3C/script%3E"));

If the script above fails to identify the jQuery object after trying to load jQuery, it will add a script tag to load jQuery from your own server. Works fine, so long as your server works too! Of course, if they don’t have Javascript enabled, you'll just have to deal with not having your library loaded at all.


blog comments powered by Disqus