Caching on the Google AJAX Libraries API

Using the Google AJAX Libraries API, there are several options for specifying the version numbers of the library you wish to use, for example the following URLs all point to the latest version – at the time of writing – of jQuery.

  1. http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js,
  2. http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js, and,
  3. http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js

The first uses the latest release in the version 1 tree, the second the latest in the version 1.3 tree, and the third the release 1.3.0 exactly. What I found interesting – and discovered accidently – is the browser caching times for each of these urls; the first two are cached for an hour, the third for twelve months.

The vastly different caching times make perfect sense, in the first two cases, the developer is expecting an upgrade to the latest version, and doesn’t want to wait up to twelve months for it; in the third case the developer doesn’t expect an upgrade so an extended caching period has no effect.

To take full advantage of the Google servers, as described in a recent article by Dave Ward, the caching times suggest it’s best to specify the full version of the library you wish to use.

google.load Method – Update Jan 24, 2009

Further investigation shows that the Google load method uses the full URL for the less specific version requests, for example the following will load ajax.googleapis.com[…]/1.3.1/jquery.min.js* – at the time of writing – and cache the file for twelve months.

<script src="http://www.google.com/jsapi"></script>
<script>
  /* <![CDATA[ */
  google.load("jquery", "1"); //latest version in the v1 tree
  /* ]]> */
</script>

The jsapi file is not cached, so a additional 5K is downloaded for every page hit on your website; if a visitor loads more than three pages an hour then the advantage of the longer caching time is lost. As always, it’s a matter of compromise.

* A minor update to jQuery has been released since the original article was written.

Published by Peter Wilson

Peter Wilson is a Senior WordPress Engineer at Human Made and contributor to WordPress core. Peter has worked on the web for twenty years on everything from table based layouts in the 90s to enterprise grade CMS development. Peter’s a big fan of musical theater and often encourages his WordPress community colleagues to join him for a show or two in New York or in the West End.