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 HostedLibrariesĀ 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: 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.
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 benefit of using the Google AJAX Libraries CDN is thatĀ your users may not need to download jQuery at all.
No matter how well optimized your site is, if youāre hosting jQuery locally then your users must download it at least once. Each of your users probably already has dozens of identical copies of jQuery in their browserās cache, but those copies of jQuery are ignored when they visit your site.
However, when a browser sees references to CDN-hosted copies of jQuery, it understands that all of those references do refer to the exact same file. With all of these CDN references point to exactly the same URLs, the browser can trust that those files truly are identical and wonāt waste time re-requesting the file if itās already cached. Thus, the browser is able to use a single copy thatās cached on-disk, regardless of which site the CDN references appear on.
This creates a potent ācross-site cachingā effect which all sites using the CDN benefit from. Since Googleās CDN serves the file with headers that attempt toĀ cache the file for up to one year, this effect truly has amazing potential. With manyĀ thousands of the most trafficked sites on the Internet already using the Google CDN to serve jQuery, itās quite possible that many of your users will never make a single HTTP request for jQuery when they visit sites using the CDN.
Even if someone visits hundreds of sites using the same Google hosted version of jQuery,Ā they will only need 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 src="https://www.google.com/jsapi"></script> <script> google.load("jquery", "1.11.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.
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 src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script> $(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.
HTTTypo?
If youāre curious why the script reference is missing the leadingĀ http:
, thatās a helpful trick which allows you to use a single reference that works on both HTTP and HTTPS pages. For more information about that and why it matters, be sure to check out this follow-up post:Ā Cripple the Google CDNās caching with a single character.
The main caveat to keep in mind when using the protocol-less reference is that it will fail on pages loaded via file:/// (i.e. HTML pages you load directly from disk to your browser). So, do be sure to include theĀ http:
Ā protocol in the URL if you happen to be developing without a web server at all, but donāt worry about omitting it otherwise.
Other implementations
WordPressĀ ā If youāre using WordPress and want to take advantage of the Google CDN throughout your WordPress site without manually editing themes, plugins, etc, check outĀ Jason PenneyāsĀ Use Google LibrariesĀ plugin.
HTML5 BoilerplateĀ āĀ H5BPĀ is a web site skeleton that provides a great starting point for building a modern site. As part of that, it uses a reference to jQuery on the Google CDN (and an automatic fallback to a local copy for users that arenāt able to load jQuery from the CDN for some reason).
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 they 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?