When to use Vanilla JavaScript vs. jQuery?
There's a framework called... oh guess what? Vanilla JS
. Hope you get the joke... :D It sacrifices code legibility for performance... Comparing it to jQuery
bellow you can see that retrieving a DOM
element by ID
is almost 35X faster. :)
So if you want performance you'd better try Vanilla JS and draw your own conclusions. Maybe you won't experience JavaScript hanging the browser's GUI/locking up the UI thread during intensive code like inside a for
loop.
Vanilla JS is a fast, lightweight, cross-platform framework for building incredible, powerful JavaScript applications.
On their homepage there's some perf comparisons:
this.id
(as you know)this.value
(on most input types. only issues I know are IE when a<select>
doesn't havevalue
properties set on its<option>
elements, or radio inputs in Safari.)this.className
to get or set an entire "class" propertythis.selectedIndex
against a<select>
to get the selected indexthis.options
against a<select>
to get a list of<option>
elementsthis.text
against an<option>
to get its text contentthis.rows
against a<table>
to get a collection of<tr>
elementsthis.cells
against a<tr>
to get its cells (td & th)this.parentNode
to get a direct parentthis.checked
to get the checked state of acheckbox
Thanks @Tim Downthis.selected
to get the selected state of anoption
Thanks @Tim Downthis.disabled
to get the disabled state of aninput
Thanks @Tim Downthis.readOnly
to get the readOnly state of aninput
Thanks @Tim Downthis.href
against an<a>
element to get itshref
this.hostname
against an<a>
element to get the domain of itshref
this.pathname
against an<a>
element to get the path of itshref
this.search
against an<a>
element to get the querystring of itshref
this.src
against an element where it is valid to have asrc
...I think you get the idea.
There will be times when performance is crucial. Like if you're performing something in a loop many times over, you may want to ditch jQuery.
In general you can replace:
$(el).attr('someName');
with:
Above was poorly worded. getAttribute
is not a replacement, but it does retrieve the value of an attribute sent from the server, and its corresponding setAttribute
will set it. Necessary in some cases.
The sentences below sort of covered it. See this answer for a better treatment.
el.getAttribute('someName');
...in order to access an attribute directly. Note that attributes are not the same as properties (though they mirror each other sometimes). Of course there's setAttribute
too.
Say you had a situation where received a page where you need to unwrap all tags of a certain type. It is short and easy with jQuery:
$('span').unwrap(); // unwrap all span elements
But if there are many, you may want to do a little native DOM API:
var spans = document.getElementsByTagName('span');
while( spans[0] ) {
var parent = spans[0].parentNode;
while( spans[0].firstChild ) {
parent.insertBefore( spans[0].firstChild, spans[0]);
}
parent.removeChild( spans[0] );
}
This code is pretty short, it performs better than the jQuery version, and can easily be made into a reusable function in your personal library.
It may seem like I have an infinite loop with the outer while
because of while(spans[0])
, but because we're dealing with a "live list" it gets updated when we do the parent.removeChild(span[0]);
. This is a pretty nifty feature that we miss out on when working with an Array (or Array-like object) instead.
The correct answer is that you'll always take a performance penalty when using jQuery instead of 'plain old' native JavaScript. That's because jQuery is a JavaScript Library. It is not some fancy new version of JavaScript.
The reason that jQuery is powerful is that it makes some things which are overly tedious in a cross-browser situation (AJAX is one of the best examples) and smooths over the inconsistencies between the myriad of available browsers and provides a consistent API. It also easily facilitates concepts like chaining, implied iteration, etc, to simplify working on groups of elements together.
Learning jQuery is no substitute for learning JavaScript. You should have a firm basis in the latter so that you fully appreciate what knowing the former is making easier for you.
-- Edited to encompass comments --
As the comments are quick to point out (and I agree with 100%) the statements above refer to benchmarking code. A 'native' JavaScript solution (assuming it is well written) will outperform a jQuery solution that accomplishes the same thing in nearly every case (I'd love to see an example otherwise). jQuery does speed up development time, which is a significant benefit which I do not mean to downplay. It facilitates easy to read, easy to follow code, which is more than some developers are capable of creating on their own.
In my opinion then, the answer depends on what you're attempting to achieve. If, as I presumed based on your reference to performance benefits, you're after the best possible speed out of your application, then using jQuery introduces overhead every time you call $()
. If you're going for readability, consistency, cross browser compatibility, etc, then there are certainly reasons to favor jQuery over 'native' JavaScript.
There's already an accepted answer but I believe no answer typed directly here can be comprehensive in its list of native javascript methods/attributes that has practically guaranteed cross-browser support. For that may I redirect you to quirksmode:
http://www.quirksmode.org/compatibility.html
It is perhaps the most comprehensive list of what works and what doesn't work on what browser anywhere. Pay particular attention to the DOM section. It is a lot to read but the point is not to read it all but to use it as a reference.
When I started seriously writing web apps I printed out all the DOM tables and hung them on the wall so that I know at a glance what is safe to use and what requires hacks. These days I just google something like quirksmode parentNode compatibility
when I have doubts.
Like anything else, judgement is mostly a matter of experience. I wouldn't really recommend you to read the entire site and memorize all the issues to figure out when to use jQuery and when to use plain JS. Just be aware of the list. It's easy enough to search. With time you will develop an instinct of when plain JS is preferable.
PS: PPK (the author of the site) also has a very nice book that I do recommend reading