Downloading and Including jQuery

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

Free book: Jump Start HTML5 Basics

Grab a free copy of one our latest ebooks! Packed with hints and tips on HTML5's most powerful new features.

  • Lars

    Maybe you don’t realise but actual version of Jquery is 1.5.1 now!

    • http://www.onsman.com Ricky Onsman

      Thanks, Lars. That’s been updated so you don’t think Earle is out-of-date.

  • Andrew

    If you have been in web development for any sort of time and you don’t know at least something about jQuery and/or Sizzler (the CSS element selection library behind jQuery), then I’m not sure what you are doing.

    Anything else besides these JS libraries we have now (jQuery and others) is a total waste of time unless you are targeting ONE browser and exactly ONE version of it.

  • McBenny

    Using Google’s CDN is a good option for all that you mentionned but are there any drawbacks ?
    Nothing is free in this world and you could consider that by using those files you will: inform Google of the existence of your site, give them all informations possible on your visitors almost as if you used Google Analytics service (as a browser allways identifies itself to the server): that includes the visit frequency, where they’re from, where they go etc.
    Don’t think evil, yes, I know, but if you look at the economic model of Google’s products, you can be sure that the cost of the bandwith and of the servers is worth… for them.

  • Steve

    I’m wondering why all jquery sample always include the library in the “head”. Yahoo YSlow specify to put all javascript in the “body” for optimisation.

    Can someone tell me the advantage of putting it in the “head”?

    • Andrew

      I agree with putting almost all JS in the body after all other HTML. Reasoning is quite simple. If you have event handlers that depend on an element existing, you’re much better off letting that load first than the JS that will attach the events.

      But, if you have something that MUST run first, you can put the JS anywhere before the end of the body, but the only other valid place besides the body is head.

      There’s no general consensus, but I agree with Yahoo on this one in 99% of cases. I truly believe most people think tag BELONGS in head ONLY.

      • kaf

        I thought there was a performance benefit with putting it in the head? Maybe I heard wrong but if nothing else it makes things neater cos it keeps all your script in one place.

        And the argument that “you have event handlers that depend on an element existing” doesn’t hold with jquery. Thats why we have this:
        $(document).ready(function(){
        //event handler stuff
        });

    • McBenny

      It’s just old fashioned.
      When the browser encounters the script src markup, it fetches the file but stops parsing the rest of the html file. With one or more large JS files, that creates a short time with a blank page on the screen before the display.
      If you put your scripts at the end of all your HTML (before /body), the browser starts to render the page immediatly.
      A draw back is when your script modifies the HTML (hides a block, clip a region…) : the browser renders what the HTML shall be then executes your JS instructions and modifies what the visitor sees : this creates a sort of flickering.

      • Web Guy

        I would disagree that it’s old-fashioned to put external scripts in the head. There are plenty of valid reasons to have a script in the head–any time you absolutely must have it run as soon as possible. That’s not old-fashioned.

        The browser doesn’t really stop parsing the rest of the HTML when it hits the script src, it just blocks downloading of additional resources like images. But there is a way around that, which is described in this article on how to increase performance: http://www.yuiblog.com/blog/2008/07/22/non-blocking-scripts/

        If you use a CDN like Google’s, the jQuery file is probably already cached so there isn’t that much of a performance hit.

  • rickydazla

    Or, the Paul Irish method:

    !window.jQuery && document.write(unescape(‘%3Cscript src=”js/libs/jquery-1.5.1.js”%3E%3C/script%3E’))

  • David Müller

    Javascript Compression != Javascript Minification. The article reads like it’s the same thing.

  • Richard

    Are you able to link directly to the Google CDN version or is an API key required?

  • Murray

    You can link directly to the Google CDN, no API key or anything is needed.

  • http://www.bhawinpatel.blogspot.com bhawin

    useful information of jquery…. i get many ideas….

  • http://www.jordar.com Jordar

    I can’t run Jquery in my site…what i do?