Gain A Better Understanding of jQuery

I've run into dozens of designers who aren't fully clear on what jQuery is. They know it's cool, they know it's useful, and they may have even followed some related tutorials, but they're confused about what it really is. Is it something that comes with a browser? Is it a way of writing code? Is it a replacement for Flash? Is it just old-fashioned black magic?

Gain A Better Understanding of jQuery


If you're a member of this group, this article is for you. I'll help you understand what jQuery really is and how you can use it. You'll be a better designer and a better web citizen for the effort!

To understand how jQuery fits into the landscape of the web, we have to first talk about JavaScript.

jQuery's Roots: A Brief History of JavaScript

An important word of clarification: Java and JavaScript are completely unrelated. Java is a programming language created by Sun in the early 1990s; JavaScript, which came along later, is an unrelated language that creatively piggy-backed on the popularity of the Java name.

Back in the day in the mid 1990s, websites were painfully static. Once you loaded a page, not much of anything would happen until you reloaded that page or loaded a new one. Interaction was non-existent.

This all changed in late 1995, when Netscape created a new programming language called JavaScript and added it to the Netscape browser. This language allowed web developers to interact with the user and manipulate a webpage after the page had loaded. This opened a whole new world of possibilities for adding interactive behavior to webpages. Because the browser took care of interpreting (running) code written in this new language, all the developer had to do was add a chunk of JavaScript code to his/her HTML page within some script tags. It was easy and offered amazing new possibilities.

Before developers could start using JavaScript, though, it had to become a standard. This quickly happened as Microsoft implemented a variation of JavaScript in Internet Explorer (the only other major browser) in 1996. With cross-browser support available, developers started using JavaScript for adding bits of interaction to pages. Things like calculators, drop-down menus and other interactive elements started appearing in web pages across the Internet.

Fast-forward to 2005. JavaScript's functionality had matured and become standard across all browsers. Along the way, a feature called XMLHttpRequest had been added. This feature (commonly referred to as "AJAX") allowed JavaScript code to communicate with a server, sending and receiving data, without the page ever being reloaded. Browsers had also added methods to perform every imaginable type of manipulation to a loaded web page's structure. (This structure is known as the DOM, short for Document Object Model.)

jQuery's Roots: A Brief History of JavaScript

Sounds great, right? Well, there was one major problem. All of the browsers had different ways of accessing all of this functionality. And beyond that, there were different bugs in each browser. If you wanted to perform a simple action like validate a form, you had to write code that checked for which browser was being used and performed browser-specific actions – all while working around numerous browser bugs.

Resourceful web developers met these challenges by writing something called JavaScript libraries. A JavaScript library is nothing more than a chunk of JavaScript code you include in your page. This chunk of code is special because it defines its own higher-level functions for accessing the JavaScript functions built into the browser. In the case of the browser disparities, these libraries defined a single function to perform a certain action (like changing the text in a specific section of a page). If you wanted to perform an action, you called the library function instead of the built-in JavaScript functions. The library would take care of detecting the browser, avoiding bugs, etc.

A (Rock)Star Is Born

Not satisfied with the complexity and missing functionality in the libraries he saw, a Rochester Institute of Technology student named John Resig set out in 2005 to create a better library. His library, named jQuery, was intended to make it fast and easy to perform common JavaScript tasks like manipulating the HTML document (DOM), communicating with a server via AJAX, listening for events and creating animation.

One of the major features he included was support for the selection of DOM elements with CSS-style syntax; this made it fast and easy to locate specific elements within a page in order to interact with or manipulate them. Additionally, jQuery was based on a highly-extensible architecture, meaning it was easy to add additional functionality and your own personal "shortcuts."

A (Rock)Star Is Born

The first preview of the new jQuery library was released in January of 2006 and instantly garnered immense attention. In addition to having a compelling feature set, it was free and open-source. In the years that followed, additional functionality was added and the library matured. And millions of developers started using it. Today, jQuery's perfect blend of simplicity, flexibility and power has helped it become the undisputed leader amongst JavaScript libraries. At the time of writing, over 25% of the top million websites and over 45% of the top 10,000 were using jQuery [reference]. Truly, jQuery has changed the face of web development.

Side Note

Have you ever looked at a chunk of JavaScript code, especially for a library like jQuery, and thought that it looked like gibberish? You were probably looking at minified JavaScript code. Minification is a process by which a program takes human-readable JavaScript and optimizes it to reduce file size. One of the most significant aspects of this is renaming variables – for example, myReallyLongVariableName becomes ab. It doesn't change what the code does; it just optimizes it for size (and also performance, in some cases). The advantage of minification is that developers can write high-quality, readable code that's easy to edit, while delivering online a highly-optimized version that's optimized for fast transfer.

jQuery vs. Flash: A "Battle" that Never Existed

One of the most common points of confusion when talking about jQuery is the relationship between jQuery and Flash. Flash is a browser plugin, a separate piece of software that runs within the browser to provide additional functionality. JavaScript, as we discussed earlier, is a part of the web browser itself – a language that's built into the browser.

In the past, it was extremely difficult, or even impossible, to create animation using just JavaScript to manipulate an HTML document. This is where Flash shone – you could quickly and easily create an animation in the Flash authoring tool. As Flash matured, you could create even highly complex, interactive animations with relative ease. You exported your Flash creation to an SWF file, then added some code in your HTML that told the browser, "use the Flash plugin to show my SWF file, someAnimation.swf." For the time, this was the perfect solution.

jQuery vs. Flash: A "Battle" that Never Existed

However, as the years passed, JavaScript and HTML matured. In the last couple of years, browsers started adding a new class of functionality called HTML 5. This functionality, part of the latest version of the HTML standard, meant that these browsers could natively perform actions previously only the Flash plugin could. Libraries like jQuery made it possible, and relatively easy, to create interactive animation that previously required Flash.

As this was all happening, the iPhone came along. It offered a mobile browsing experience unparalleled by any other mobile device. For a number of reasons, however, Steve Jobs decided that the Flash plugin would not be allowed on the iPhone (and later iPad as well). This highly controversial decision soon affected web designers and developers in a major way. As the use of iPhones and iPads exploded, designers and developers had to either re-create their Flash content in JavaScript + HTML, provide a dumbed-down fallback for mobile visitors, or risk alienating mobile visitors by leaving a site that wasn't iPhone/iPad compatible.

Thus, if there were a battle at all, it would be between HTML + JavaScript vs. Flash, not jQuery vs. Flash. But there is no real battle – there are just different ways to do the same thing. For some projects, Flash is the better tool and offers functionality that's simply not built into any browser, even the most cutting-edge ones. For other projects, though, the built-in technologies of JavaScript and HTML are the better choices.

The complication that has hurt Flash's ability to compete (and consequently encouraged a conversion process) is Apple banning Flash from the iPhone and iPad. As Flash becomes less relevant, jQuery is simply a powerful tool that reduces the pain of transition from a plugin-based technology (Flash) to built-in browser technologies (JavaScript and HTML / HTML5).

How jQuery is Added To Your Page

When including JavaScript in your page, you can either include the code directly within the HTML of the page like this:

<script type="text/javascript"> ... </script>

or call in an external file that holds a chunk of JavaScript. Here's what an external JavaScript reference looks like:

<script type="text/javascript" src="mystuff.js"></script>

This tells the browser to load the JavaScript in the mystuff.js file, and run it as though it were all right there within the HTML of the page. Whenever you have lots of JavaScript, especially if it's going to be re-used in multiple pages, it should be placed in an external file that's called in by reference.

This ensures the best possible loading performance on your page, by automatically taking advantage of features like browser caching. As we covered before, JavaScript libraries (like jQuery) are nothing more than great-big snippets of JavaScript code. Because they're relatively large and are used across multiple pages, such libraries should always be stored in a separate file.

How jQuery is Added To Your Page

To use jQuery in your page, you have to load an external file that holds the library's JavaScript code. To do this, you simply include a reference to the jQuery file in your HTML page (usually at the top), like this:

<script type="text/javascript" src="somepath/jquery-1.6.1.min.js"></script>

Where do you get the JavaScript file that's referenced? There are two possible sources for the file – you can reference a copy you have on your own server, or a copy that's hosted by someone else. Originally, hosting on your own server was the only method used; it is still relatively common today. You go to jQuery and download the latest version of the jQuery JavaScript file. You take this file, which holds all of the library's JavaScript code, save it within your site, and then use a reference like the example above to call it into your pages.

While there are benefits to this method (namely, having it fully under your control), there are also downsides. Every visitor to your website has to download the library, which requires time and bandwidth. This extra load can also slow down your server. Consider another factor – if your server is in Los Angeles, for example, and a user is browsing your site in Paris, the JavaScript file has to be transferred around the world. This takes time and contributes unnecessary traffic to the Internet pipes between LA and Paris.

As a solution to these issues and a service to the community, Google provides complimentary hosting of popular JavaScript libraries like jQuery on their ultra-tuned distribution network. Considering they handle over 6 percent of all traffic on the Internet, Google has one of the best (perhaps the best) content distribution networks in the world. When a request is made to their network, the request is automatically routed to a datacenter that is geographically near the requester.

Using our earlier example, the visitor in Paris would receive a file hosted in Paris or London, not Los Angeles. This significantly reduces transfer time and helps reduce unnecessary Internet traffic. Another major benefit of referencing a Google-hosted copy of jQuery stems from caching advantages.

Because there are millions of websites referencing the same file that Google hosts – many of them major ones that people visit often, chances are good that a visitor to your website will have already downloaded the jQuery library from Google when they arrive at your site. In this case, their browser will have already cached a copy of the library on their computer, and the browser will use this local copy instead of re-downloading it from the Internet.

This again speeds up your website and reduces unnecessary Internet traffic. To top it all off, Google also automatically delivers a compressed version of the JavaScript file whenever possible, further reducing the amount of data that must be transferred. You can do this yourself, but it requires special server setup.

The end result of using Google's free jQuery hosting? Better performance for all of your visitors, and less load on your server. If you want more technical details about the local vs. Google-hosted jQuery decision, here's a compelling argument in favor of letting Google do it (with a follow up).

So, how does one go about referencing the Google-hosted copy of jQuery instead of a local copy? The appropriate URLs can be retrieved from this page. (Many other libraries are available on that page, too.) Here's an example reference:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6/jquery.min.js"></script>

The decision is up to you, but using the Google-hosted version is definitely worthy of consideration.

How jQuery is Referenced When Writing JavaScript

Once you've included the jQuery JavaScript file into your page, you can reference it in any JavaScript code farther along in your page. This is where the dollar sign you're probably already familiar with comes in. All of the jQuery library functions can be accessed through a single jQuery function; but, as a shorthand convenience, they're also accessible by using the $ function.

How jQuery is Referenced When Writing JavaScript

The dollar sign isn't anything special from a syntactical perspective – to the browser's JavaScript interpreter, it's just a function name. It could just as easily be myBigFatLibrary, but that would obviously be slower and more difficult to type!

When dealing with jQuery code, you'll often see code wrapped like this:

$(function(){     ...code here...  });

This is simply a shorthand way of referencing the jQuery.ready function. The code in the passed function is called as soon as the webpage has loaded sufficiently that manipulation may begin. To ensure proper execution, jQuery functions should always be called from within the ready handler as shown.

Summary

In this tutorial, I've helped you gain a solid understanding of what exactly jQuery is, what it does, and how you add it to your page. With this foundation, you're ready to jump into the millions of getting started with jQuery tutorials available on the web. Have fun adding new functionality and amazing effects to your web pages. Who knows – maybe someday you'll write your own jQuery plugin or even JavaScript library!