Serving your jQuery from a public CDN (Content Delivery Network) can arguably offer several advantages to your website, especially if you don’t use a fast server to host it. If you’re not familiar with both sides of the arguments, please check the two attached links below as there’s no points to repeat the subject over the advantages vs. disadvantages of hosting jQuery from a CDN.
PROS – 3 reasons why you should let Google host jQuery for you (broken – 4/26/2017)
CONS – Should You Use JavaScript Library CDNs?
If you ever decide to use CDN jQuery, you can choose to serve the javascript library from one of the three official CDN jQuery hosts (Google, Microsoft, and jQuery) that are listed on the jQuery download page. With the first two as most popular, you can host your jQuery from Google CDN or Microsoft’s. Another host that’s also worth mentioning is cdn js.
You just need to hotlink to any of the CDN you want to use in your source attribute:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"> </script>
That’s it!
But of course things can go wrong with the CDN server or the routing and for any other bizarre reasons the javascript file is just not available. This scenario can be avoided by creating a fallback method to serve the jQuery from our own website. We can do this by adding the second line (line 4-6):
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"> </script> <script> !window.jQuery && document.write('<script src="/js/jquery-1.12.4.min.js"></script>') </script>
If you don’t think this technique is sufficient, there are more techniques that might suit your need better from the two links below:
A Simple and Robust jQuery 1.4 CDN Failover in One Line
How and Why: CDN Hosted jQuery with a Local Fall-Back Copy (broken – 5 July 2014)
Most Popular jQuery CDN Links
All three links are listed in the order of popularity. Just use one jQuery CDN link as your source.
Google CDN
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
jQuery’s CDN
<script src="//code.jquery.com/jquery-1.12.4.min.js"></script>
Microsoft CDN
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.12.4.min.js"></script>
Further Reading
Tips on how to add CDN jQuery for WordPress (Genesis Framework) users
Leave a Reply