Including jQuery in Your Pages

Course- Javascript >

Many JavaScript libraries are available, but jQuery is arguably the most popular and also the most extensible. A huge number of developers contribute open source plug-ins for jQuery, and you can find a suitable plug-in for almost any application you might have. The wide range of plug-ins and the simple syntax make jQuery such a great library. In this section you learn the basics of jQuery and get a taste of how powerful it is.


Including jQuery in Your Pages

Before you can use jQuery, you need to include it in your pages. There are two main options, as detailed in the following sections.

Download jQuery

You can download jQuery from the official website at http://docs.jquery.com/Downloading_jQuery, where you find both Compressed and Uncompressed versions of the code. The Compressed version is for your live pages, as it has been compressed to the smallest possible file size to download as quickly as possible.

For development purposes, choose the Uncompressed version. Thanks to the wellformatted, commented source, you can read the jQuery code to see how it works.

You need to include the jQuery library in the <head> section of your pages, using a <script> tag. The easiest way is to place the downloaded jquery.js file in the same directory as the page from where you want to use it and then reference it like this:

<script src="jquery-1.11.2.js"></script>

Of course, if you place jQuery in another directory, you’ll have to change the (relative or absolute) path in the value you give to the src attribute to reflect the location of the file.

Use a Remote Version

Instead of downloading and hosting jQuery yourself, you can include it from a so-called Content Delivery Network, or CDN. In addition to saving you from having to download the jQuery library, using a CDN version has a further advantage: It’s quite likely that when users visit your page and their browser requests jQuery, it’ll already be in their browser cache. Additionally, CDNs generally ensure that they serve the file from the server geographically closest to them, further cutting the loading time.

The official jQuery site currently lists the following CDNs:

You can then modify your <script> tag to suit the chosen CDN, for example:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>

Unless you have a particular reason for hosting jQuery yourself, this is usually the best way.