Loading jQuery using Content Delivery Network (CDN)

There exist some different ways to add jQuery to a web page. The idea of this challenge is to describe one of the possibilities, which is using a Content Delivery Network (CDN), or more particularly using Google Hosted Libraries.
1 answer

Loading jQuery using Google Hosted Libraries

There are two ways of adding jQuery to a web page:

- Using local copy of jQuery, which can be downloaded from their official website, or
- Via adding a link to one of the online versions of jQuery, which are located on different servers. This is the so called Content Delivery Network (CDN). This can be done for example by using Google Hosted Libraries.

CDN is actually a network of servers located on different places of the world. When the user opens a web page, the static resources (like images, jQuery, CSS files, etc.) are downloaded from the nearest possible server. The biggest benefit of that is that the page will load faster.
Google Hosted Libraries serves as a “home” for the most popular JavaScript libraries like jQuery, MooTools, AngularJS, etc. This is a service presented by Google, which in my opinion is very secure and reliable. This is the main reason I use it and recommend it.

Adding jQuery using Google Hosted Libraries:

Step 1)
Go to the Google Hosted Libraries web page (https://developers.google.com/speed/libraries/) where you can get more information about the service.

Step 2)
Find the jQuery library in the list of JavaScript libraries. There you can find the text which you should copy. After that there is some version information about the latest versions of jQuery.

Step 3)
Copy the snippet text, open the HTLM document you want to put it in and paste it in the . The corresponding code will look like that:

01. < head >
02. …
03. < script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js" >< /script >
04. < /head >

Step 4)
The code from above will work perfectly, but only after your site is online. In order for it to work offline (on your computer) you should add the protocol the browser would use to connect to the file.

01. < head >
02. …
03. < script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js" >< /script >
04. < /head >

The difference is in the additional “https” at the beginning of the “src” attribute. That will allow your browser to connect the file even if you are working from your computer.

Step 5)
In order to test if it is working you also put some other jQuery text in the like:
01. < head >
02. < script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js" >< /script >
03. < script type="text/javascript" >
04. $(document).ready(function(){
05. alert('jQuery successfully added!');
06. });
07. < /head >

Step 6)
Save the existing code and open the page in a browser. We will get an alert saying “jQuery successfully added” if everything went well.

Taggings: