Quick tip: Use a CDN to host your favorite scripts

Quick tip: Use a CDN to host your favorite scripts

When building website, most probably you will be using Javascript frameworks like jQuery or Mootools to enhance your website. Obviously you will grab a copy of the library from their homepage and link it in your web pages, then upload together to your web space. Well, why not using CDN to host your favorite script?

I found three content delivery networks (CDN) that host some of the most commonly used scripts in the world: Google Libraries API, Microsoft Ajax CDN and CDNJS. Google Libraries is the popular one, but hosts lesser scripts compared to CDNJS. The latter hosted a really huge amount of scripts including Modernizr and many more. And why we should use CDN instead of hosting on our own?

Benefits

Well, by using CDN, you will have less files to host on your server thus saving more bandwidths. Second, is because many people are using them to host the script as well. That means that probably the visitors already cached a copy into their local drive and page loading will be much faster. To learn more, please read “3 reasons why you should let google host jQuery for you” by Dave Ward.

CDN hosted script with fallback

Here I’m going to show you the recommended way of using CDN hosted script (jQuery for example) with fallback to your local copy, according to HTML5 Boilerplate. In this example, I will be using jQuery. The first script tag shows the source link to Google Libraries API, while the second one is the fallback code to link to your own local copy.

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

Using the older version of jQuery

Both Google Libraries API and Microsoft Ajax CDN host the older version of jQuery. Microsoft’s provides links for each versions, while for Google, you can just change the version number to the older one, like below.

// Just change the 1.7.1 to the older version (eg. 1.6.4)
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>

So, here is the quick tip that I want to show you today. Hope you like it!

Similar Posts:

Comments