Using a Content Delivery Network to host jQuery

A Content Delivery Network (CDN) is a system of computers that exist all over the world and cache files for users to access. CDNs can greatly reduce the load time of a page by offering files at a higher bandwidth from a server that is physically closer to your visitor than your web server might be.

Web developers can leverage the use of CDNs (and the good graces of Google and Microsoft) to host their jQuery Library for faster access and improved performance.

Why should I use a CDN to host jQuery?

  • The jQuery library download time will be reduced. Your users in Europe will hit the CDN in Europe and your users in the US should hit the US CDN. As a result, this will reduce your overall page load time.
  • The jQuery library will already be cached in the visitor's browser if they visited another website that references the same jQuery library. In this case, the visitor won't even have to download the jQuery library.
  • It's free!

How do I use a CDN to host jQuery?

Luckily for us, both Microsoft and Google already host jQuery on their CDNs. All we have to do now is reference the hosted jQuery library. It doesn't matter which one you use, I'm sure most people just decide based on which company they like better.

For Microsoft:

<head>
  <script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery/jquery-1.6.1.min.js"></script>
</head>

For Google:

<head>
  <script type="text/javascript"   src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
</head>

What if the CDN is down?

So, the above method is all fine and good, but what if your user can't access the CDN for some reason? This would cause all of your super-cool jQuery features to stop working and essentially break your website causing your user to have flashbacks of the late 1990's. How tragic!

As a backup option you can still host jQuery on your web server and only reference it if your visitor somehow fails to load the CDN hosted jQuery library.

Add this method below your CDN jQuery reference. This code will check to see if jQuery is loaded and if it isn't the script will load the jQuery library from your web server.


Now you can take advantage of the benefits of the CDN and still have a contingency plan if for some reason the CDN is unavailable.

As a final note, this solution is really geared for internet sites where you will have users from all over the world. For intranet sites, you are probably better of hosting jQuery locally on the intranet.

Creative Commons License

What do you think?