What’s so good about jQuery?

The following article is the first in an online series based on excerpts fom jQuery: Novice to Ninja, by Earle Castledine & Craig Sharkie (2010, SitePoint).

You’ve read that jQuery makes it easy to play with the DOM, add effects, and execute Ajax requests, but what makes it better than, say, writing your own library, or using one of the other (also excellent) JavaScript libraries out there?

First off, did we mention that jQuery makes it easy to play with the DOM, add effects, and execute Ajax requests? In fact, it makes it so easy that it’s downright good, nerdy fun—and you’ll often need to pull back from some craziness you just invented, put on your web designer hat, and exercise a little bit of restraint (ah, the cool things we could create if good taste were not a barrier!). But there are a multitude of notable factors you should consider if you’re going to invest your valuable time in learning a JavaScript library.

Cross-browser Compatibility

Aside from being a joy to use, one of the biggest benefits of jQuery is that it handles a lot of infuriating cross-browser issues for you. Anyone who has written serious JavaScript in the past can attest that cross-browser inconsistencies will drive you mad. For example, a design that renders perfectly in Mozilla Firefox and Internet Explorer 8 just falls apart in Internet Explorer 7, or an interface component you’ve spent days handcrafting works beautifully in all major browsers except Opera on Linux. And the client just happens to use Opera on Linux. These types of issues are never easy to track down, and even harder to completely eradicate.

Even when cross-browser problems are relatively simple to handle, you always need to maintain a mental knowledge bank of them. When it’s 11:00 p.m. the night before a major project launch, you can only hope you recall why there’s a weird padding bug on a browser you forgot to test!

The jQuery team is keenly aware of cross-browser issues, and more importantly they understand why these issues occur. They have written this knowledge into the library—so jQuery works around the caveats for you. Most of the code you write will run exactly the same on all the major browsers, including everybody’s favorite little troublemaker: Internet Explorer 6.

This feature alone will save the average developer a lifetime of headaches. Of course, you should always aim to keep up to date with the latest developments and best practices in our industry—but leaving the task of hunting down obscure browser bugs to the jQuery Team (and they fix more and more with each new version) allows you more time to implement your ideas.

CSS3 Selectors

Making today’s technologies cross-browser compliant is all well and good, but jQuery also fully supports the upcoming CSS3 selector specification. Yes, even in Internet Explorer 6.0! You can gain a head start on the future by learning and using CSS3 selectors right now in your production code. Selecting elements you want to change lies at the heart of jQuery’s power, and CSS3 selectors give you even more tools to work with.

Helpful Utilities

Also included is an assortment of utility functions that implement common functions useful for writing jQuery (or are missing from JavaScript!): string trimming, the ability to easily extend objects, and more. These functions by themselves are particularly handy, but they help promote a seamless integration between jQuery and JavaScript which results in code that’s easier to write and maintain.

One noteworthy utility is the supports function, which tests to see if certain features are available on the current user’s browser. Traditionally, developers have resorted to browser sniffing—determining which web browser the end user is using, based on information provided by the browser itself—to work around known issues. This has always been an unsatisfying and error-prone practice. Using the jQuery supports utility function, you can test to see if a certain feature is available to the user, and easily build applications that degrade gracefully on older browsers, or those not standards-compliant.

jQuery UI

jQuery has already been used to make some impressive widgets and effects, some of which were useful enough to justify inclusion in the core jQuery library itself. However, the jQuery team wisely decided that in order to keep the core library focused, they’d separate out higher-level constructs and package them into a neat library that sits on top of jQuery.

That library is called jQuery User Interface (generally abbreviated to just jQuery UI), and it comprises a menagerie of useful effects and advanced widgets that are accessible and highly customizable through the use of themes. Some of these features are illustrated in Figure 1.1, “A few jQuery UI widgets”.

Figure 1.1. A few jQuery UI widgets

Falling in Love with jQuery

Accordions, sliders, dialog boxes, date pickers, and more—all ready to be used right now! You could spend a bunch of time creating them yourself in jQuery (as these have been) but the jQuery UI controls are configurable and sophisticated enough that your time would be better spent elsewhere—namely implementing your unique project requirements rather than ensuring your custom date picker appears correctly across different browsers!

We’ll certainly be using a bunch of jQuery UI functionality as we progress through the book. We’ll even integrate some of the funky themes available, and learn how to create our own themes using the jQuery UI ThemeRoller tool.

Plugins

The jQuery team has taken great care in making the jQuery library extensible. By including only a core set of features while providing a framework for extending the library, they’ve made it easy to create plugins that you can reuse in all your jQuery projects, as well as share with other developers. A lot of fairly common functionality has been omitted from the jQuery core library, and relegated to the realm of the plugin. Don’t worry, this is a feature, not a flaw. Any additional required functionality can be included easily on a page-by-page basis to keep bandwidth and code bloat to a minimum.

Thankfully, a lot of people have taken advantage of jQuery’s extensibility, so there are already hundreds of excellent, downloadable plugins available from the jQuery plugin repository, with new ones added all the time. A portion of this can be seen in Figure 1.2, “The jQuery plugin repository”.

Figure 1.2. The jQuery plugin repository

Falling in Love with jQuery

Whenever you’re presented with a task or problem, it’s worth checking first to see if there’s a plugin that might suit your needs. That’s because almost any functionality you might require has likely already been turned into a plugin, and is available and ready for you to start using. Even if it turns out that you need to do some work yourself, the plugin repository is often the best place to steer you in the right direction.

Keeping Markup Clean

Separating script behavior from page presentation is best practice in the web development game—though it does present its share of challenges. jQuery makes it a cinch to completely rid your markup of inline scripting, thanks to its ability to easily hook elements on the page and attach code to them in a natural, CSS-like manner. jQuery lacks a mechanism for adding inline code, so this separation of concerns leads to leaner, cleaner, and more maintainable code. Hence, it’s easy to do things the right way, and almost impossible to do them the wrong way!

And jQuery isn’t limited to meddling with a page’s existing HTML—it can also add new page elements and document fragments via a collection of handy functions. There are functions to insert, append, and prepend new chunks of HTML anywhere on the page. You can even replace, remove, or clone existing elements—all functions that help you to progressively enhance your sites, thus providing a fully featured experience to users whose browsers allow it, and an acceptable experience to everyone else.

Widespread Adoption

If you care to put every JavaScript library you can think of into Google Trends, you’ll witness jQuery’s exponential rise to superstardom. It’s good to be in the in crowd when it comes to libraries, as popularity equates to more active code development and plenty of interesting third-party goodies.

Countless big players on the Web are jumping on the jQuery bandwagon: IBM, Netflix, Google (which both uses and hosts the jQuery library), and even Microsoft, which now includes jQuery with its MVC framework. With such a vast range of large companies on side, it’s a safe bet that jQuery will be around for some time to come—so the time and effort you invest in learning it will be well worth your while!

jQuery’s popularity has also spawned a large and generous community that’s surprisingly helpful. No matter what your level of skill, you’ll find other developers patient enough to help you out and work through any issues you have. This caring and sharing spirit has also spread out to the wider Internet, blossoming into an encyclopedia of high quality tutorials, blog posts, and documentation.

What’s the downside?

There barely is a downside! The main arguments against using any JavaScript library have always been speed and size: some say that using a library adds too much download bloat to pages, while others claim that libraries perform poorly compared with leaner custom code. Though these arguments are worth considering, their relevance is quickly fading.

First, as far as size is concerned, jQuery is lightweight. The core jQuery library has always had a fairly small footprint—about 19KB for the basics, less than your average JPG image. Any extras your project needs (such as plugins or components from the jQuery UI library) can be added in a modular fashion—so you can easily count your bandwidth calories.

Speed (like size) is becoming a decreasing concern as computer hardware specifications rise and browsers’ JavaScript engines grow faster and faster. Of course, this is far from implying that jQuery is slow—the jQuery team seem to be obsessed with speed! Every new release is faster than the last, so any benefit you might derive from rolling your own JavaScript is shrinking every day.

When it comes to competing JavaScript libraries (and there are more than a handful out there), jQuery is the best at doing what jQuery does: manipulating the DOM, adding effects, and making Ajax requests. Still, many of the libraries out there are of excellent quality and excel in other areas, such as complex class-based programming. It’s always worth looking at the alternatives, but if the reasons we’ve outlined appeal to you, jQuery is probably the way to go.

But enough talk: time for jQuery to put its money where its mouth is!

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.

  • bas

    Personally, I think that JQuery sucks.

    The API is just weird, why not choosing for a weird $ function instead of a clean object-oriented API?

    I prefer to create my own javascript applications. It would have been great to have some cross-browser tools but the code structure of jquery is so bad that I rather create my own codebase than using jquery and having 2 coding styles mixed.

    • Ricardo Costa

      Maybe you could release your code base, it could prove you’re right!

      I’m tagging this on http://ogr3.com/jquery for future reference.

    • Rafa

      Probably you are not developing professional applications.

      In my spare time I also reinvent the wheel for fun!

  • deathshadow

    Given that even compressed that fat bloated pile of manure is almost half the size I allocate as the ideal for an entire PAGE on a site (that’s HTML+images+CSS+scripts) and that uncompressed it’s almost 50% larger and two-thirds my upper limit…

    … and given that NOTHING in this article gave me any reason to believe that the fat bloated gee-aint-it-neat animated crap that chews up most of it’s size and the idiotic execution time chewing “oh noes I have to type getelementbyid without jquery” nonsense is worth dealing with…

    Seriously, HOW ARE PEOPLE SO GULLIBLE as to think that jquery is worth using in the first place — half of the scripts I’ve seen are usually SMALLER if written without it, and the other half are stupid bandwidth wasting animated garbage that has no place on a website in the first place and in fact GETS IN THE WAY of a decent user experience.

    But with people blowing half a megabyte or more these days on delivering 2K’s of plaintext and flushing accessibility down the toilet with broken/bloated/useless scripting…

    • Anonymous

      Let’s see, nowadays web based rich apps kick ass and many many large companies use apps with web interface, be it CRM or anything alike.

      It is so narrow-minded labeling jQuery as “pile of manure” just because your work is so trivial that you’ll never need anything that jQuery and UI offers. Had you ever had the need for an actual rich app that someone who’s not proficient with computers can use – meaning creating various elements hinting what each part of the page does – you probably wouldn’t be spouting such elitist-wannabe nonsense.

      jQuery definitely speeds up the development process, especially in conjunction with the UI. Haters will always be there, hopefully someone with actual knowledge and history of use of jQuery might contribute a comment underlining the shortcomings in a polite, non-ill-mannered way.

      • deathshadow

        As a user, so called “rich apps” end up broken, annoying and inferior on most every website that tries to use them compared to a conventional non-scripted site…

        As a developer they are a maintennance headache from hell that take something simple and turn it into an overcomplicated mess…

        … and I have YET to see a script that is any simpler, easier, or better using jquery— or would even have taken longer to develop than it would without it.

        Frankly, these “web apps” with two or three rare exceptions are guaranteed to turn me into a bounce.

      • Anonymous

        I disagree with you deathshadow. It saves so much time and effort to code. jQuery UI is great I have to have to spend endless hours search web or write my own Calendar Widgets in JavaScript. With jQuery to implement it take couple seconds, and I don’t need to worry if it will work in IE, Firefox, Opera, Safari or Chrome. So sounds like you are living under the rock it’s time to relocate.

    • Vectorfrog

      You do know that if you reference the jquery file located on google’s server instead of hosting the file on your own server, you are all but guaranteed that the file will already have been cached within the user’s browser, right?

    • awasson

      deathshadow, you have to come up with some new material. I half read this article just to see how many comments in it would take you to start your rant.

      I have agreed with some of your past comments on the state of the internet, markup, etc. and I’m of the opinion that markup should be as squeaky clean as possible when it hits the browser but… I think the audience of this article are doing a little more than filling input fields with getelementbyid. Todays browsers are more capable and like it or not todays clients want more interactivity.

      The point of using jQuery or some other library isn’t to fill in a form field or two, or give wizbang effects without reason, it is to provide a framework that can be called upon for heavy lifting for all of your scripting needs. For instance, you’re building a boutique website that features scaling background images to fit the window’s width/height, it has a portfolio slideshow with fading transitions, you also have a form that requires validation and the client section has several dozen clients so you decide to organize all of the clients by industry and then tab between them. You could spend a while writing it from scratch or you can use jQuery compressed and harness it’s functions with several dozen lines of initialization code. Then when you decide to extend the code, it uses a standardized API with documented hooks rather than whatever hand rolled code you came up with and the associated comments. When used in this capacity, I would wager that jQuery would be a lighter solution compared to hand rolled Javascript.

      I’ve rolled my own crossbrowser AJAXY code and it is pretty darned good but that was before I dug into libraries like jQuery. For the ease of extending and maintaining factor alone, I will always take the library or framework route. Yes, if I’m only validating fields or changing a few values I might roll my own code

    • Jeff

      26k is half the size of your page for everything? so 52k for your whole site? Is your page a h2 and then a p tag and thats it? You sound like a reputable source of information. You must not use jquery, because you dont have room for any javascript at all on your sites regardless I guess.

    • dme3

      If you’ve ever developed serious RIA’s in javascript you would not be talking like this. jQuery is a huge time saver and once you get used to the syntax it yields fairly elegant code. It actually shortens alot of your own custom code and the maintainability of the codebase is awesome. As a bonus, the way it forces you to write your code in a certain way turns it into a great communication tool, helping others to understand your code more easily.
      I’ve been developing javascript-heavy web applications for years (i’m talking actual functional applications, mostly intranets and administrative tools, not your avarage content focused websites with js-sprinkles on top) and i must say i was a bit skeptical about jQuery at first, but once i started using it… WOW!
      Of course you could stay stuck in the nineties and try to make a case against interactive websites, but face it… javascript is here to stay and any tools with such widespread community support, great plugins, shallow learning curve and definite benefits in both development time and code maintainability should be welcomed with open arms.

  • Dan

    I use jQuery on a daily basis, but to state there are basically no downsides is bit off. Everything in life has pros and cons, and jQuery is no exception. jQuery is extremely well suited for general development and rapid development. However, there is something about the syntax (chaining, use of functions, etc) which often leads to poorly written code that becomes hard to maintain.

    Yes, poorly written code is the developers fault, but I have found when using jQuery in larger applications that the code quickly becomes hard to follow. This is because it is incredibly easy to do something ‘the jQuery way’ instead of making proper use of design patterns, separating out event handling logic from business logic, etc.

  • TiTi

    Speed and size are so not the main downside of jQuery.
    I’d say:
    - It’s not stable
    - jQuery plugin ecosystem is messy
    - jQuery (UI) is young

    jQuery is mostly dedicated to document traversing, event handling, animating, and Ajax interactions.
    jQuery UI & custom plugins are used to build fonctionnal tools on top of them, but jQuery doesn’t integrate them initially. That’s a very important thing to know before choosing jQuery as a framework !

    jQuery is very good, but doesn’t provide the structure and the components you can find directly into others frameworks, for instance YUI2.

    jQuery brings a new way of coding, probably closer to JS language than other frameworks, but also trickier (each(), closures, this, chaining, …).

    Anyway I’m a huge fan of jQuery even if I don’t consider it stable enough.

    jQuery 2.0 version is approching and it’s a major rewrite so…

  • G

    I am halfway through the jQuery From Novice to Ninja book, and I love it!
    Thanks for writing it,
    G

  • Paul

    Not to nit-pick, but jQuery 1.5 is now 29k. It’s still well compressed, but it is slightly larger then the 19k reported.

  • Shadow Caster

    JQuery is brilliant. I’m not a very good javascript coder but it was quick and easy to learn JQuery (a big plus) compared to YUI, and the code was so sleek, simple and powerful and just makes things so much faster to develop. It made coding some stuff like Ajax enjoyable. I think my main issue with it now is that it’s getting bigger and bigger with each release. They should take it easy and just support, suggest and improve plugins for when people need that extras.

  • techuth

    JQuery is the best thing to use in any website. It is simple and more attractive. Thanks for this post.

  • DN

    Thank You so much to make it really clear about jQuery, It came at the perfect time.

  • Saleh

    Did I just buy the book to have it published online for free? not to mention the code base is already fully available.

  • Roach

    Hello,

    Can someone tell me how good YUI3 is compared to Jquery?
    please suggest me which one to work on.

    Thanks
    Roach

  • Anonymous

    IBM is one of the most important supporters and contributors to Dojo, and I hardly doubt they are “are jumping on the jQuery bandwagon”

  • Anonymous

    Dojo also is a good toolkit.

  • Slo

    First of all, great article, if I had to explain the major benefits of jQuery to anybody, I would rather send him/her this link.

    I’m working now for a while with jQuery and I had good and bad times (mostly good). These guys that are bul**** about performance and other stuff, are I believe some kids with no real development experience. I’m working on a large scale application and we are using jQuery. The application does a lot of AJAX and makes heavy use of jQuery UI (in short it almost resembles a desktop environment). We do a mix of good old OO JavaScript and use of jQuery as someone already said for the heavy lifting. I can agree with some people about the kind of strange syntax, but for the benefits you get, this point is almost nonsense. I’ve done some heavy JavaScript programming before, and I have to admit that jQuery saves time and makes you focus on more important things rather then dealing with cross browser issues. The guys around jQuery are really guys that know what they are doing and there are hardly bigger problems you can run in (of course if you know what you are doing). One can argue about many things, but in the end what matters is the value that your customer gets in the shortest time possible, and jQuery does that for sure.

    As this is a post about jQuery, I made my point about it particularly, but I think that most libraries out there are probably as good if not better, the only thing you need to consider is which one suites best to your needs. One is sure, I would always go for a JavaScript framework than doing things from scratch, as one of the main risks in web development is cross-compatibility, and if someone solved this issues for me, why should I reinvent the wheal?

  • MonkeyBoy

    Jquery isn’t even a framework. A framework IMHO would be more akin to Backbone, Cappuccino, or Sproutcore
    Jquery gives very little in the way of benefit for building RIA if you consider that most of the UI components need to come from 3rd parties. Jquery UI is also limited in features, so you need to leverage these plugins a great deal. Now you have an additional bunch of problems:
    1) bloated widgets in your app – you don’t necessarily need full functionality yet the widgets you use are large and overfeatured.
    2) version control and update issues with each widget from various sources – try keeping up to date and not breaking anything
    3) compatibility and collision issues between multiple 3rd party widgets.
    Debugging hell
    If you are extending beyond simple DOM decoration, you will hit a wall. Try building a complex desktop app with floating MDI windows etc sometime with jquery only. Try to find some standard in the plugs you need to use. Or even a decent floating window.

  • Andy R

    I’ve been using JavaScript for years, and also VB.NET, and I find JQuery leaves a lot to be desired, as

    1) The syntax is absolutely horrible (and this is from someone who is skilled at regular expressions).

    2) It’s really hard to debug if something goes wrong.

    3) Having seen what a proper framework looks like (the clean, discrete objects in Microsoft.NET – this is NOTHING LIKE it.

    It needs to be re-written as a series of powerful objects in a more verbose manner.