The jQuery CDN is a way to include jQuery in your website without actually downloading and keeping it your website’s folder. There are a number of jQuery CDNs which you can use, examples – Google, Microsoft, Cloudflare, jQuery own CDN & more.
Normally we all first download & put the jQuery file in the website’s folder. Then we reference this file on the page head section.
<head> <script src="files/jquery-3.2.1.min.js"></script> </head>
Instead we can use jQuery CDN by just providing the link of jQuery directly from Google, Microsoft, CloudFlare, etc.
So when using jQuery from the jQuery’s own CDN, you can do:
<head> <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script> </head>
Notice the src path that links to jQuery file from code.jquery.com domain.
In the same way we can use jQuery CDN hosted by Google, as shown below:
<head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> </head>
Microsoft also hosts jQuery and this CDN is used below:
<head> <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script> </head>
CloudFlare is a great CDN and also very popular too. It also has jQuery CDN which you can use in your website.
<head> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> </head>
When you use jQuery CDN then you are actually doing 2 positive things:
a. The CDN hosted jQuery might be blocked by a filter or proxy service on the user’s connnection.
b. The CDN is down or timing out, since the browsers typically have a timeout of 30 seconds therefore the jQuery fails to load in these conditions.
Luckily there is a simple solution for these CDN issues. You can easily provide a locally-hosted fallback version of jQuery. The basic idea for CDN fallback is to check for a type or variable that should be present after a script loads. If it’s not there then try getting the jQuery file locally.
Notice the escape characters inside the document.write method.
Or, slightly differently.
// First try loading jQuery from CDN <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script> // If the CDN fails then Fallback to a local copy of jQuery <script> window.jQuery || document.write('<script src="/js/jquery-3.2.1.min.js"><\/script>')) </script>