At Techorama 2014, Nik Molnar mentioned very shortly that you should use CDNs. CDNs, or Content Delivery Networks (or Distribution), are public repositories of javascript libraries, css files, images, etc that anyone can reference.

There are lots of CDNs out there. A popular one is Google Hosted Libraries. You’ll find Angular, jQuery, jQuery UI, etc.

The main advantage of using a CDN is performance. There’s a good chance that people who visit your site will already have visited a site referencing the same libraries/files. If these were hosted on a the same CDN that you are referencing, your browser will fetch the file from its own cache. That’s one less HTTP request, and increased speed in loading the file.

An added bonus is that it doesn’t use up your bandwidth 🙂

One thing Nik mentioned very briefly was to have a fallback mechanism in case the CDN doesn’t respond. However, he didn’t go into how this works.

A CDN that is down shouldn’t happen (often), but knowing the internet, it will. If your site is a low profile, small throwaway test-site, there’s no problem. If your site is more crucial and has lots of visitors, it pays to have this fallback, as it’s very simple.

Instead of just referencing the CDN like this:

<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

You can check for the existence of a variable the library defines. If it doesn’t exist, load the local version of the file:

<script>
    window.jQuery
     || document.write('<script src="js/libs/jquery-2.1.1.min.js"><script>')
</script>

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

This site uses Akismet to reduce spam. Learn how your comment data is processed.