Google AJAX Libraries API
Were you aware that Google has a Content Delivery Network that serves up some of the most popular javascript libraries on the web? Hopefully you were. And hopefully you’re already using it. But. There’s that oddball chance that you’re not, so use this post as motivation to get started.
In addition to sheer convenience, here are three more reasons why you should let Google host your javascripts: decreased latency, increased parallelism, and better caching.
Click out to that link (here it is again) to get the details.
I must say, though, I’m not a fan of the google.load() method, even though that’s what Google recommends.
1 2 3 4 |
<script src="http://www.google.com/jsapi"></script>
<script>
google.load("jquery", "1");
</script
|
Doing that removes the reliability of things like $(document).ready(), because you’d have to wait for the load() function to finish, well, loading the library. There’s a way around that by using the google.setOnLoadCallback() and passing it a function, but eh. I just don’t like it.
So I include the libraries directly. That’s the easiest (and fastest) way to take advantage of this CDN.
And if your a Rails developer, you’re in for another treat. A while ago I wrote a plugin, cleverly called google_ajax_libraries_api, that allows you to make use of this in a Rails-esque sort of way.
1 | $ script/plugin install git://github.com/rpheath/google_ajax_libraries_api.git |
Then you can do things like this:
1 2 3 4 5 6 7 8 | <%= google_yui -%> <%= google_mootools -%> <%= google_jquery :version => '1.2.3' -%> <%= google_jqueryui -%> <%= google_prototype :uncompressed => true -%> <%= google_scriptaculous -%> <%= google_swfobject -%> <%= google_dojo :version => '1.1.1', :uncompressed => true -%> |
Of course, you typically wouldn’t use all of them at the same time :-)
The plugin will use the highest supported version of each library, unless explicitly told otherwise. Also, if you’d rather pass a few libraries at once, you can do:
1 | <%= google_javascripts :prototype, :jquery, :jqueryui -%> |
Note: using the google_javascripts helper, you cannot set explicit versions.
The plugin supports all of the libraries currently supported by Google (so far there are eight), and I typically update the plugin within a day of any Google updates/changes.
So, no more excuses. Let Google host your javascripts.

Alchan Thursday, 12 Mar, 2009 Posted at 07:06AM
Quite cool!