All too often, I find code similar to this when inspecting the source for public websites that use jQuery:


<script type="text/javascript" src="/js/jQuery.min.js"></script>

If you’re doing this on a public facing* website, you are doing it wrong.


Instead, I urge you to use the Google AJAX Libraries content delivery network to serve jQuery to your users directly from Google’s network of datacenters. Doing so has several advantages over hosting jQuery on your server(s): decreased latency, increased parallelism, and better caching.

In this post, I will expand upon those three benefits of Google’s CDN and show you a couple examples of how you can make use of the service.

Update (11/6/09): Since you’re reading this post, you may also be interested to know that Google also hosts full jQuery UI themes on the AJAX APIs CDN.


* None of this is relevant to internal applications served over a LAN. It would be as likely harm performance as improve it.

Decreased Latency

A CDN — short for Content Delivery Network — distributes your static content across servers in various, diverse physical locations. When a user’s browser resolves the URL for these files, their download will automatically target the closest available server in the network.

In the case of Google’s AJAX Libraries CDN, what this means is that any users not physically near your server will be able to download jQuery faster than if you force them to download it from your arbitrarily located server.


There are a handful of CDN services comparable to Google’s, but it’s hard to beat the price of free! This benefit alone could decide the issue, but there’s even more.

Increased parallelism

To avoid needlessly overloading servers, browsers limit the number of connections that can be made simultaneously. Depending on which browser, this limit may be as low as two connections per hostname.

Using the Google AJAX Libraries CDN eliminates one request to your site, allowing more of your local content to downloaded in parallel. It doesn’t make a gigantic difference for users with a six concurrent connection browser, but for those still running a browser that only allows two, the difference is noticeable.

Better caching


Potentially the greatest (yet least mentioned) benefit of using the Google AJAX Libraries CDN is that your users may not need to download jQuery at all.

No matter how aggressive your caching, if you’re hosting jQuery locally then your users must download it at least once. A user may very well have dozens of identical copies of jQuery-1.3.2.min.js in their browser’s cache, but those duplicate files will be ignored when they visit your site for the first time.

On the other hand, when a browser sees multiple subsequent requests for the same Google hosted version of jQuery, it understands that these requests are for the same file. Not only will Google’s servers return a 304 “Not Modified” response if the file is requested again, but also instructs the browser to cache the file for up to one year.

This means that even if someone visits hundreds of sites using the same Google hosted version of jQuery, they will only have to download it once.

Implementation

By now, you’re probably convinced that the Google AJAX Libraries CDN is the way to go for your public facing sites that use jQuery. So, let me show you how you can put it to use.


Of the two methods available, this option is the one that Google recommends:

The google.load() approach offers the most functionality and performance.

For example:


<script type="text/javascript" 
        src="http://www.google.com/jsapi"></script>

<script type="text/javascript">
  // You may specify partial version numbers, such as "1" or "1.3",
  //  with the same result. Doing so will automatically load the 
  //  latest version matching that partial revision pattern 

  //  (e.g. 1.3 would load 1.3.2 today and 1 would load 1.4.1).
  google.load("jquery", "1.4.1");
 
  google.setOnLoadCallback(function() {

    // Place init code here instead of $(document).ready()
  });
</script>

While there’s nothing wrong with this, and it is definitely an improvement over hosting jQuery locally, I don’t agree that it offers the best performance.

Firebug image of the longer loading time caused by jsapi

As you can see, loading, parsing, and executing jsapi delays the actual jQuery request. Not usually by a very large amount, but it’s an unnecessary delay. Tenths of a second may not seem significant, but they add up very quickly.


Worse, you cannot reliably use a $(document).ready() handler in conjunction with this load method. The setOnLoadCallback() handler is a requirement.

Back to basics

In the face of those drawbacks to the google.load() method, I’d suggest using a good ‘ol fashioned <script> declaration. Google does support this method as well.

For example:


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

<script type="text/javascript">
  $(document).ready(function() {
    // This is more like it!
  });

</script>

Not only does this method avoid the jsapi delay, but it also eliminates three unnecessary HTTP requests. I prefer and recommend this method.

Conclusion

According to a recent study, Google will consume 16.5% of all consumer Internet capacity in the United States during 2008. I think it’s fair to say that those guys know how to efficiently serve up some content.

The opportunity to let the pros handle part of your site’s JavaScript footprint free of charge is too good to pass up. As often as even returning users experience the “empty cache” load time of your site, it’s important to take advantage of an easy optimization like this one.


What do you think? Are you using the Google AJAX Libraries CDN on your sites? Can you think of a scenario where the google.load() method would perform better than simple <script> declaration?

I wonder why hasn’t this been done for MicrosoftAjax.js?

Update: Microsoft now provides a similar service for MicrosoftAjax.js.