Using Google’s CDN to load JavaScript libraries

For rich Ajax web applications page loading time suffers from loading JavaScript libraries such as JQuery, MooTools, Prototype etc..  Most of them are larger than 50KB in size and if you are in need to combine libraries then you are adding 100KB+ to your page loads.

Also your web server will experience delivery of your own hosted JavaScript libraries across distinct geographical requests. You can easily offload your server for those files.

Assuming all possible ways to improve JavaScript libraries loading time, Google’s CDN aka Google Libraries API can be a good solution.

Why Google CDN? Why not my own server?

  • The Google Libraries API is a content distribution network and loading architecture for the most popular, open-source JavaScript libraries.
  • Google’s huge CDN (content delivery network) can deliver the file much. Since Google has large data centers all over the world, these files will be served from data centers geographically closer to your users. This helps to reduce network latency and add to reliability, scalability and so on.
  • The more sites that include Google’s google.load() API the greater the chance that a user has already has the file cached, thus enabling your site to load faster as the script will not need to be downloaded.
  • You save bandwidth as you no longer have to serve the file(s).
  • The versioning system that Google has created makes it effortless to include specific versions of these libraries.

All you need to do is make a Google’s Libraries API call google.load() like:

<script src="" type="text/javascript"></script>

google.load("chrome-frame", "1.0.2");
google.load("dojo", "1.5");
google.load("ext-core", "3.1.0");
google.load("jquery", "1.4.2");
google.load("jqueryui", "1.8.4");
google.load("mootools", "1.2.4");
google.load("prototype", "");
google.load("scriptaculous", "1.8.3");
google.load("swfobject", "2.2");
google.load("yui", "2.8.1");
google.load("webfont", "1.0.6");


Minor Drawbacks

  • You’re dependent on the CDN infrastructure. If they are down, your website will be hardly usable, too.  But that case u have to write extra codes to check the desired library loaded or not.
  • You cannot influence bandwidth and carriers of the delivery provider’s network.




Updating your page dynamically with Ajax.Updater – Prototype API


Well most of web devs desire Ajax to update parts of the document by receiving HTML fragments. If I assume right that you are one of them then this one is for you. Also we are going to approach below in Prototype.js way 🙂

By the way, Are you a jQuery lover? If yes, then you should know jQuery(1.4.x) doesn’t provide such facility directly  😉

Normally in prototype.js – ajax, we execute Ajax.Request(Click here in case ur not familiar with it) to make our asynchronous requests.

In order to update part of your HTML document with HTML fragments, with Ajax.Request with an onComplete callback this is fairly easy, but with Ajax.Updater it’s even easier! 😀

Ajax.Updater: Performs an AJAX request and updates a container’s contents based on the response text.

Lets have some real example below:

Suppose you have such a portion in your HTML document

<h2>List of My Girlfriends </h2>
<!-- By the way, how many GF do you have? -->
<div id="girlfriends">(fetching girlfriends list ...)</div>

And you are suppose to fill that “girlfriends” DIV with…

new Ajax.Updater('girlfriends', 'gfManager.php', { method: 'get' });

That’s all. 🙂 No hassle… It will update your “girlfriends” DIV with girlfriends name list.

And your server end script responded well and looks like below:

<h2>List of My Girlfriends </h2>
<div id="girlfriends">
<li> Emma Watson </li>
<li> Nora Ali </li>
<li> Jessica Parker </li>

The arguments are the same of Ajax.Request, except there is the receiver element in the first place. Prototype will automagically update the container with the response using the Element.update() method.

And if you are smart enough you can implement this one in your own way.

Here i built my own username availability checker at some user signup page:

<label for="username">username:</label>
<input type="text" name="username" id="username" onkeyup="checkUserName();" />
<div id="availability"></div>

with this checkUserName method

function checkUserName() {
 if($F('username').length == 5) {
 var url = 'chkusername.php';
 var params = 'username=' + $F('username');
 var ajax = new Ajax.Updater(
 {success: 'availability'},
 {method: 'get', parameters: params, onFailure: reportError});
function reportError(request) {
 $F('availability') = "Error";

The server end script does query the database and responds whether the username taken or not.
Which looks like below:

If the username is available

If the username is already taken

Cheers! 😀

Ajax with Prototype JavaScript framework

Before starting with Prototype AJAX, if you wish to have some basic Ajax talks you can visit my previous post


Prototype is a JavaScript Framework which provides an Ajax framework and other utilities. It offers a familiar class-style OO framework, extensive Ajax support, higher-order programming constructs, and easy DOM manipulation.

I love Prototype Framework due its robustness all the way 😀

Prototype’s Ajax

Besides simple requests, this module also deals in a smart way with JavaScript code returned from a server and provides helper classes for polling.

Ajax functionality is contained in the global Ajax object. Actual requests are made by creating instances of the Ajax.Request object.

Ajax.Request (All you need for using AJAX in Prototype API)

new Ajax.Request('/some_url', { method:'get' });
//Initiates and processes an AJAX request.

The first parameter is the URL of the request; the second is the options hash.
method option refers to the HTTP method to be used; default method is POST.

As Ajax requests are by default asynchronous so you must have Callbacks in order to handle server response data and those callback methods should be passed in the options hash.

Ajax response callbacks

new Ajax.Request('/some_url',
 onSuccess: function(transport){
 var response = transport.responseText || "no response text";
 alert("Success! \n\n" + response);
 onFailure: function(){ alert('Something went wrong...') }

Here, two callbacks are passed in the hash that alert of either success or failure; onSuccess and onFailure are called accordingly based on the status of the response.
Other available callbacks are:

  • onUninitialized,
  • onLoading,
  • onLoaded,
  • onInteractive,
  • onComplete and
  • onException.

They all match a certain state of the xmlHttpRequest transport, except for onException which fires when there was an exception while dispatching other callbacks.

Parameters with the request

You can pass the parameters for the request as the parameters property in options:

new Ajax.Request('/some_url', {
  method: 'get',
  parameters: {name: 'Tonu', age: 27}

The main idea to use parameter option is sending the contents of FORM with the request and yes of-course Prototype has it’s helper to do serialize.

new Ajax.Request('/some_url', {
  parameters: $('id_of_form_element').serialize(true)

Global responders

Again if you wish to register some callbacks which will fire on certain state and will work with every Ajax.Request
then you have
Ajax.Responders, a repository of global listeners notified about every step of Prototype-based AJAX requests.

If you wish extend your reading then Click Here

More on Ajax with Prototype Here

Cheers! 😀

Ajax with jQuery.ajax() – jQuery API

Before approaching Ajax, I must say that I have seen lots of newbie programmer who are lil bit confused about “What is Ajax?”

But before digging into Ajax, lets review the non-common sense about Ajax

Ajax is  –

a) Not A Programming language 😦

b) Not a pattern

c) Not a Library itself

d) Not a framework itself

e) Not a tool itself

f) Not a function

g) Not a Technology itself, but a group of technologies.

Surprisingly some big guys call Ajax is a programming language!!!! WTF!

Interestingly  from an article at MacWorld: View that portion as Image

The above MacWorld article was written by Michael DeAgonia, Computerworld LOLz!!!

Let’s get into the real story of Ajax

Ajax (shorthand for asynchronous JavaScript and XML) is a programming technique or approach used on the client-side to retrieve data from the server asynchronously in the background without interfering with the display and behavior of the existing page. Data are usually retrieved using the XMLHttpRequest object. Despite the name, the use of XML is not actually required, nor do the requests need to be asynchronous.

AJAX requests are usually faster than regular page loads and allow for a wealth of dynamism within a page. 😀

Now come to the point, we talking about Ajax with jQuery and I am assuming that you have some idea of how to use jQuery.

The jQuery library has a full suite of AJAX capabilities. The functions and methods therein allow us to load data from the server without a browser page refresh.

jQuery.ajax() (Perform an asynchronous HTTP (Ajax) request.)

type: "POST", //default is "GET" HTTP request method
url: "myProject/myajax.php", //url(String)
data: "call=login&user=foo&pass=bar", //data form of an url query string
timeout: (60*1000), //timeout (in milliseconds) for the request

//function to be called if the request fails.
error: function(XMLHttpRequest, textStatus, errorThrown){
//here goes the error handler codes
//function to be called if the request succeeds.
success: function(data, textStatus, XMLHttpRequest){
//here goes the successful response handler codes
//will have the retrieved server response within this function

Sounds cool 😀

Lets make our jQuery Ajax more handy by using some sort of ajax settings, A default settings can be set Globally for any option with $.ajaxSetup().


url: "myProject/myajax.php", //my page to process
global: false,
timeout: (60*1000), //set timeout for all your ajax requests
cache: false, //say no to cache 😦
contentType: 'application/x-www-form-urlencoded', //is default actually(no need)
type: "POST" //if you love to post always
error: function(){ myDefaultErrorHandlerFunc(); } //set your default error handler
//The avobe setting will act like your global jQuery.ajax() settings throughout the page
//Now simple making ajax requests like below
data: {'name': 'Tonu'}, //key value paired (JSON style) or can like "call=login&name=Tonu"
success: function(xh){}

Awesome 🙂

So using $.ajaxSetup() once, you can place your ajax shortly like above $.ajax({data:”queryString”});  in your code wherever it requires.

Some more jQuery.ajax() usage example:

Load and execute JavaScript file

   type: "GET",
   url: "test.js",
   dataType: "script"

Sends an xml document as data to the server. By setting the processData option to false, the automatic conversion of data to strings is prevented.

var xmlDocument = [create xml document];
   url: "page.php",
   processData: false,
   data: xmlDocument,
   success: handleResponse

Cheers! 😀

What? Boared?!!! Why not take a deep breath and lough out loudly.. 😉