Why to use Google hosted jQuery CDN

Google is sea of free services. Do you know that Google is also hosting jQuery libraries on its CDN(Content delivery network) and allows any website to use it for free. But why to use Google hosted jQuery CDN?


  • Caching: The most important benefit is caching. If any previously visited site by user is using jQuery from Google CDN then the cached version will be used. It will not be downloaded again.
  • Reduce Load: It reduces the load on your web server as it downloads from Google server's.
  • Serves fast : You will be also benefitted from speed point of view. As Google has dozen's of different servers around the web and it will download the jQuery from whichever server is closer to the user. Google's CDN has a very low latency, it can serve a resource faster than your webserver can.
  • Parellel Downloading: As the js file is on a separate domain, modern browsers will download the script in parallel with scripts on your domain.

How to use it?

There are 2 ways to load from Google CDN.

Method 1:
<script  type="text/javascript"
Method 2
<script src="http://www.google.com/jsapi" type="text/javascript"></script>
<script type="text/javascript"><!--
google.load("jquery", "1.7.1");
google.setOnLoadCallback(function() {
// Place init code here instead of $(document).ready()
// -->

What if Google CDN is down?

It is a good idea to use CDN but what if the CDN is down (rare possibility though) but you never know in this world as anything can happen. So if you have loaded your jQuery from any CDN and it went down then your jQuery code will stop working and your client will start shouting.

Hang on, there is a solution for this as well. Below given jQuery code checks whether jQuery is loaded from Google CDN or not, if not then it references the jQuery.js file from your folder.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
if (typeof jQuery == 'undefined')
  document.write(unescape("%3Cscript src='Scripts/jquery.1.7.1.min.js' type='text/javascript'%3E%3C/script%3E"));
It first loads the jQuery from Google CDN and then check the jQuery object. If jQuery is not loaded successfully then it will references the jQuery.js file from hard drive location. In this example, the jQuery.js is loaded from Scripts folder.

Few tips

If you want jQuery 1.7.1 you can use a url like this:
Suppose you want to use latest version of 1.7 release,
If you always want to refer the latest version of jQuery,
Feel free to contact me for any help related to jQuery, I will gladly help you.

Nothing shocks me, I'm a Software Engineer. And I am not young enough to know everything. I live in World Wide Web and from there take care of this website. This website communicates about my work, learning and experience. I believe life is short, and it is for loving, sharing, learning and connecting. So lets connect..