jQuery: An Introduction
- No need to worry about browser inconsistencies.
- Shorter, easier-to-maintain code.
- Access to useful, powerful widgets from other developers to make our work easier.
How jQuery Works
When including jQuery, you have the option of downloading it from the jQuery website and hosting it on your own site or you can link to it from a CDN (Content Delivery Network) where it is hosted for you. Consider these two examples:
Both are examples of how we might include the jQuery library on a given web page. (Note that we would choose one or the other, but not both, of these options.) In the first case, we include jQuery from Google's CDN. The benefit here is performance - caching (your users' browser may already have cached that version jQuery from Google), increased parallelism (that is, avoiding the limits some browsers make on number of simultaneous downloads from one hostname), and decreased latency (given that Google's hosting is certain to be fast and, with many distributed servers, likely as not to be physically closer to your users than your hosting server), and the price (free) is pretty good to say the least. Using a CDN is generally the way to go.
The second case shows how you might link to the jQuery library that you download from the jQuery website and host on your own web server, in a directory named "js". The advantages here are that you have the code - it's on your site. You are not relying on an external provider - which could (though, in Google's case, that seems unlikely) go down - to serve a key part of your page.
Whichever strategy you choose, it is a good idea to use the minified version of jQuery; note the "min" in the file names in the examples above. Minification is the process of stripping whites pace and using shorter identifiers for variable and function names, significantly cutting down the size (and thus the download time) of the file. The minified version works exactly the same as the un-minified version; it's best to use the minified version for production sites.
Running Code on Document Ready
Often we will wrap our jQuery code in the ready handler. This ensures that the jQuery code we write does not execute until the DOM has loaded but (usefully) does not wait until all images have downloaded.
Here's a quick example: