How to load jQuery from Google’s CDN with local fallback

Google provides open source JavaScript libraries from its CDN. Its Google Libraries API is a content distribution network for the most popular JavaScript files. It is advantageous to load scripts from Google’s CDN because of several reasons. One is better caching of the code. Users probably already has dozens of identical copies of jQuery in their browser’s cache. So the total download weight of the site is remarkably reduced. Even there is no cache then it would be downloaded from the nearest Google CDN server, which will still be faster than downloading it from our site because it will be downloading in parallel from a different host.

Another advantage of fetching script from the Google’s CDN is that it will release some overload of our server. Using the Google Libraries CDN eliminates one request to our site, allowing more of our local content to downloaded in parallel. This will eventually help in improving the performance of our site.
The only disadvantage is that if the connection to the CDN were to fail, our site would be left with no jQuery library which could be a big deal if we run a jQuery intensive website. If it happens then there should be some mechanism to fetch the library from other source or from our own locally hosted location.

How to implement?

This is fairly easy and short. Only two lines of code will do the job. In first line, script is fetched from the Google’s CDN. Second line will grab the library locally if the CDN is unable to provide the script.

<script  src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"  ></script>
<script>
document.write(unescape('%3Cscript  type="text/javascript" src="js/jquery-1.7.2.min.js"  %3E%3C/script%3E'));
</script>

Leave a Reply

Your email address will not be published. Required fields are marked *