Programming
Article
By Earle Castledine

Downloading and Including jQuery

By Earle Castledine
Last chance to win! You'll get a... FREE 6-Month Subscription to SitePoint Premium Plus you'll go in the draw to WIN a new Macbook SitePoint 2017 Survey Yes, let's Do this It only takes 5 min

Before you can fall in love with jQuery (or at least, judge it for yourself) you need to obtain the latest version of the code and add it to your web pages. There are a few ways to do this, each with a couple of options available. Whatever you choose, you’ll need to include jQuery in your HTML page, just as you would any other JavaScript source file.

It’s Just JavaScript!

Never forget that jQuery is just JavaScript! It may look and act superficially different—but underneath it’s written in JavaScript, and consequently it’s unable to do anything that plain old JavaScript can’t. This means we’ll include it in our pages the same way we would any other JavaScript file.

Downloading jQuery

This is the most common method of acquiring the jQuery library—just download it! The latest version is always available from the jQuery web site. The big shiny download button will lead us to the Google code repository, where we can grab the latest “production compression level” version.

Click the download link and save the JavaScript file to a new working folder, ready for playing with. You’ll need to put it where our HTML files can see it: commonly in a scripts or javascript directory beneath your site’s document root. For the following example, we’ll keep it very simple and put the library in the same directory as the HTML file.

To make it all work, we need to tell our HTML file to include the jQuery library. This is done by using a script tag inside the head section of the HTML document. The head element of a very basic HTML file including jQuery would look a little like this:

<head>

  <title>Hello jQuery world!</title>

  <script type='text/javascript' src='jquery-1.5-min.js'></script>

  <script type='text/javascript' src='script.js'></script>

</head>

The first script tag on the page loads the jQuery library, and the second script tag points to a script.js file, which is where we’ll run our own jQuery code. And that’s it: you’re ready to start using jQuery.

We said earlier that downloading the jQuery file is the most common approach—but there are a few other options available to you, so let’s have a quick look at them before we move on. If you just want to start playing with jQuery, you can safely skip the rest of this section.

The Google CDN

An alternative method for including the jQuery library that’s worth considering is via the Google Content Delivery Network (CDN). A CDN is a network of computers that are specifically designed to serve content to users in a fast and scalable manner. These servers are often distributed geographically, with each request being served by the nearest server in the network.

Google hosts several popular, open-source libraries on their CDN, including jQuery (and jQuery UI—which we’ll visit shortly). So, instead of hosting the jQuery files on your own web server as we did above, you have the option of letting Google pick up part of your bandwidth bill. You benefit from the speed and reliability of Google’s vast infrastructure, with the added bonus of the option to always use the latest version of jQuery.

Another benefit of using the Google CDN is that many users will already have downloaded jQuery from Google when visiting another site. As a result, it will be loaded from cache when they visit your site (since the URL to the JavaScript file will be the same), leading to significantly faster load times. You can also include the more hefty jQuery UI library via the same method, which makes the Google CDN well worth thinking about for your projects: it’s going to save you money and increase performance when your latest work goes viral!

There are a few different ways of including jQuery from the Google CDN. We’re going to use the simpler (though slightly less flexible) path-based method:

<head>

  <title>Hello jQuery world!</title>

  <script type="text/javascript" src="http://ajax.googleapis.com/

  ➥ajax/libs/jquery/1.5.1/jquery.min.js"></script>

  <script type='text/javascript' src='script.js'></script>

</head>

It looks suspiciously like our original example—but instead of pointing the script tag to a local copy of jQuery, it points to one of Google’s servers.

Obtaining the Latest Version with Google CDN

If you look closely at the URL pointing to Google’s servers, you’ll see that the version of jQuery is specified by one of the path elements (the 1.5.1 in our example). If you like using the latest and greatest, however, you can remove a number from the end of the version string (for example, 1.5) and it will return the latest release available in the 1.5 series (1.5.1, 1.5.2, and so on). You can even take it up to the whole number (1), in which case Google will give you the latest version even when jQuery 1.6 and beyond are released!

Be careful though: there’ll be no need to update your HTML files when a new version of jQuery is released, but it will be necessary to look out for any library changes that might affect your existing functionality.

If you’d like to examine the slightly more complex “Google loader” method of including libraries, there’s plenty to read about the Google CDN on its web site.

Nightlies and Subversion

Still more advanced options for obtaining jQuery are listed on the official Downloading jQuery documentation page. The first of these options is the nightly builds. Nightlies are automated builds of the jQuery library that include all new code added or modified during the course of the day. Every night the very latest development versions are made available for download, and can be included in the same manner as the regular, stable library.

And if every single night is still too infrequent for you, you can use the Subversion repository to retrieve the latest up-to-the-minute source code. Subversion is an open-source version control system that the jQuery team uses. Every time a developer submits a change to jQuery, you can download it instantly.

Beware, however: both the nightly and Subversion jQuery libraries are often untested. They can (and will) contain bugs, and are subject to frequent changes. Unless you’re looking to work on the jQuery library itself, it’s probably best to skip these options.

Uncompressed or compressed?

If you had a poke around on the jQuery download page, you might have also spied a couple of different download format options: compressed (also called minified), and uncompressed (also called “development”).

Typically, you’ll want to use the minified version for your production code, where the jQuery source code is compressed: spaces and line breaks have been removed and variable names are shortened. The result is exactly the same jQuery library, but contained in a JavaScript file that’s much smaller than the original. This is great for reducing bandwidth costs for you, and speeding up page requests for the end user.

The downside of the compressed file is readability. If you examine the minified jQuery file in your text editor (go on!), you’ll see that it’s practically illegible: a single line of garbled-looking JavaScript. The readability of the library is inconsequential most of the time, but if you’re interested in how jQuery is actually working, the uncompressed development version is a commented, readable, and quite beautiful example of JavaScript.

Anatomy of a jQuery Script

Now that we’ve included jQuery in our web page, let’s have a look at what this baby can do. The jQuery syntax may look a little bit odd the first time you see it, but it’s really quite straightforward, and best of all, it’s highly consistent. After writing your first few commands, the style and syntax will be stuck in your head and will leave you wanting to write more.

The jQuery Alias

Including jQuery in your page gives you access to a single magical function called (strangely enough) jQuery. Just one function? It’s through this one function that jQuery exposes hundreds of powerful tools to help add another dimension to your web pages.

Because a single function acts as a gateway to the entire jQuery library, there’s little chance of the library function names conflicting with other libraries, or with your own JavaScript code. Otherwise, a situation like this could occur: let’s say jQuery defined a function called hide (which it has) and you also had a function called hide in your own code, one of the functions would be overwritten, leading to unanticipated events and errors.

We say that the jQuery library is contained in the jQuery namespace. Namespacing is an excellent approach for playing nicely with other code on a page, but if we’re going to use a lot of jQuery (and we are), it will quickly become annoying to have to type the full jQuery function name for every command we use. To combat this issue, jQuery provides a shorter alias for accessing the library. Simply, it’s $.

The dollar sign is a short, valid, and cool-looking JavaScript variable name. It might seem a bit lazy (after all, you’re only saving five keystrokes by using the alias), but a full page of jQuery will contain scores of library calls, and using the alias will make the code much more readable and maintainable.

Using Multiple Libraries

The main reason you might want to use the full jQuery call rather than the alias is when you have multiple JavaScript libraries on the same page, all fighting for control of the dollar sign function name. $ is a common function name in several libraries, often used for selecting elements. If you’re having issues with multiple libraries, check out Section 3.1, “Avoiding Conflicts”.

Dissecting a jQuery Statement

We know that jQuery commands begin with a call to the jQuery function, or its alias. Let’s now take out our scalpels and examine the remaining component parts of a jQuery statement. Figure 1.3, “A typical jQuery statement” shows both variants of the same jQuery statement (using the full function name or the $ alias).

Figure 1.3. A typical jQuery statement

jQuery selectors

Each command is made up of four parts: the jQuery function (or its alias), selectors, actions, and parameters. We already know about the jQuery function, so let’s look at each of the other elements in turn. First, we use a selector to select one or more elements on the web page. Next, we choose an action to be applied to each element we’ve selected. We’ll see more and more actions as we implement effects throughout the book. And finally, we specify some parameters to tell jQuery how exactly we want to apply the chosen action. Whenever you see jQuery code, try to break it up into these component parts. It will make it a lot easier to comprehend when you’re just starting out.

In our example above, we’ve asked the selector to select all the paragraph tags (the HTML <p> tags) on the page. Next, we’ve chosen jQuery’s css action, which is used to modify a CSS property of the paragraph elements that were initially selected. Finally, we’ve passed in some parameters to set the CSS color property to the value blue. The end result? All our paragraphs are now blue! We’ll delve deeper into selectors and the css action in Chapter 2, Selecting, Decorating, and Enhancing.

Our example passed two parameters (color and blue) to the css action, but the number of parameters passed to an action can vary. Some require zero parameters, some accept multiple sets of parameters (for changing a whole bunch of properties at once), and some require that we specify another JavaScript function for running code when an event (like an element being clicked) happens. But all commands follow this basic anatomy.

note:Want more?

Check out the book and buy it online at jQuery: Novice to Ninja, by Earle Castledine & Craig Sharkie

Login or Create Account to Comment
Login Create Account
Recommended
Sponsors
Get the most important and interesting stories in tech. Straight to your inbox, daily.
Is it good?Is it good?