5

Is there any advantage to using querySelector() vs jQuery's $() in a userscript? I want the script to work in all major browsers that support userscripts, so I'm especially interested in cross-browser compatibility.

I started to wonder about this because I noticed honestbleeps' excellent Reddit Enhancement Suite includes jQuery as a dependency, but mostly sticks to querySelector() for selecting elements and other basic JavaScript methods for DOM manipulation.

Is it just a matter of taste, or is there a reason to keep jQuery use to a minimum?

Brock Adams
  • 90,639
  • 22
  • 233
  • 295
Rubicon
  • 379
  • 2
  • 9
  • 2
    I wouldn't read too much into that mix in the *Reddit Enhancement Suite*. In any big or evolving project, you'll find a mix of older-style code that (mostly) works, along with newer or better practices. (Newer is not necessarily better though.) ... Very few developers or teams will refactor old working code just to make everything consistent. – Brock Adams Feb 09 '13 at 01:42

2 Answers2

4

The only reason to use querySelector() or querySelectorAll() is if you are not using jQuery. jQuery selectors are more powerful and more likely to perform consistently across browsers than advanced CSS selectors.

That said, including jQuery can needlessly complicate simple scripts. It requires Script Injection on most browsers -- which defeats sandboxes, creates potential conflicts, and makes your script dependent on a third-party server.
Here is a cross-browser way to include jQuery that minimizes conflicts. And, if the browser supports local jQuery copies, it doesn't require a third-party server to always be up/fast.

If the script is simple and you can avoid jQuery without much effort, use querySelector(). Your script will work on all script-able browsers, 99+ percent of the time.

If the script loads jQuery anyway, use jQuery selectors for maximum power and consistency.

Note that for any but the most basic DOM manipulation, jQuery is usually worth the costs. And for Firefox+Greasemonkey or Chrome+Tampermonkey, there is almost no drawback to using jQuery if you @require it.

Community
  • 1
  • 1
Brock Adams
  • 90,639
  • 22
  • 233
  • 295
1

querySelector is not supported in some browser versions, whereas jQuery's $() is.

Ryan Bigg
  • 106,965
  • 23
  • 235
  • 261
  • 2
    Doesn't apply for `greasemonkey` and `userscripts` questions. All recent editions of scriptable browsers support `querySelector()`. (At least among the standard vendors) – Brock Adams Feb 09 '13 at 00:45