Wednesday, 6 May 2009

Using the Google Ajax Libraries API

Google Logo

The Google Ajax Libraries API is a caching service for popular JavaScript libraries. Essentially, instead of loading your favorite library from your own web server, you get to use a Google URL to load the library. Since Google has all sorts of caching and edge services, this should load your library and your page much faster. In addition, if other sites use the same service, chances are your lib could already be cached in the browser. So how do you use the service?

Easy Mode

The easiest way to use the server is to just update your script tag to use a Google URL. For example, to use the latest version of JQuery I would simply use this script tag.

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

That is pretty much a slam dunk. Available URLs for JQuery, Dojo, etc... are listed in the documentation.

Fast Mode?

According to Google, the fastest and most flexible way to load the library is with the google.load() method. So the above script tag is replaced with a call to the Google jsapi library. Here is a sample of head section from my JQuery-Examples page.

 4:<head>
5: <title>JQuery Examples</title>
6: <meta name="keywords" content="jquery, form, val, html, validation"></meta>
7: <script type="text/javascript" language="javascript" src="pages.js"></script>
8: <?php include($_SERVER['DOCUMENT_ROOT'] . "/in/cssblip.php"); ?>
9: <script src="http://www.google.com/jsapi"></script>
10: <script>
11: // Load jQuery
12: google.load("jquery", "1.3.2", {uncompressed:true});
13:
14: function pageLoad(){
15: // do stuff when DOM is ready
16:
17: $('table#mainTable tbody tr:odd').addClass('oddTable');
18: $('table#mainTable tbody tr:even').addClass('evenTable');
19:
20: }
21:
22: google.setOnLoadCallback(pageLoad);
23: </script>
24:
25:</head>
26:<body>

Basically, you load the jsapi libary which in turn loads JQuery. Apparently, the compressed version of the library is loaded by default, given that, I added the third parameter to the load method. Firebug tells me that the jsapi lib is 5k and JQuery is about 35k so I think I'm getting the minified version. Also, the documentation suggests I use google.setOnLoadCallback to detect page load instead of the similar JQuery function.

Summary

So to sum up. If you want simple, go with the first option. If you want fastest, go with option 2. Either way, your Ajax enabled pages are gonna load a lot faster. Thanks Google!

No comments:

Post a Comment