JQuery CDN with fall back to local file

If you are still hosting jQuery yourself, then I guess you missed the memo about serving files from a CDN (Content Delivery Network). Basically all that you need to know is that you gain several advantages by serving the jQuery library from a CDN.

Advantages

Better caching is achieved  because over 40% of websites use jQuery and many of them use Google’s CDN which means that there is a good chance that your website users will not even have to download jQuery.

Better parallelism occurs because a CDN frees your browser up to download another resource at the same time. Browsers have a limited number of resources that can be downloaded at a time per host, with some only able to download 2 resources at a time.

Lower latency is achieved because a CDN is generally faster than your hosting server. The reasoning is that a CDN uses multiple servers across the world and chooses the nearest one based on the user’s location which decreases latency.

Other advantages of a CDN are less load & less bandwidth use on your server.

Disadvantage

The only disadvantage is that if the connection to the CDN were to fail, your site would be left with no jQuery library which could be a big deal if you run a jQuery intensive website.

Luckily, there is a solution to that problem.  This simple solution gives you the power of serving  jQuery from a  CDN while providing you with a fallback to your own hosted jQuery library for safety.

Simple jQuery fallback code:

The first part is a basic call to download the jQuery script from Google’s CDN.  The second part checks for the presence of jQuery and if it is not detected, it sets up a local version of jquery to be loaded.


Donate Bitcoins
Posted Under: Jquery Tips & Tricks
Tagged:

Author

Written by Joey Iodice

I'm a software developer focusing on ASP.net, HTML5, jQuery, & Javascript.

0 Comments

No comments yet, be the first to comment.

Leave a Reply