7 ms·
Native equivalents of jQuery functions
- deleted 14y ago[deleted]
- MattBearman 14y agoquerySelectorAll is great, assuming you know your users aren't using IE 6 / 7. Cross browser support is really where jQuery shines. jQuery is starting to become less relevant as newer browsers start to include the same functionality natively, and I say that as a massive fan of jQuery.
- jbri 14y agoWhy not use a polyfill to get the same functionality on older browsers? That also gives you the benefits of better performance on browsers that do support the native version.
- ckuijjer 14y agojQuery uses getElementsByID, getElementsByClassName etc. when available in the browser. There is only a small overhead in parsing the selector to see if it's e.g. a simple ID or class selector.
- octatone2 14y agoOr should create a DOM element. I think the main pitfall of $() is that it tries to be too many things at once. Node creation and selection should be two separate slimmed down functions. There's no need (other than convenience) for selection and creation exist in the same function.
- onion2k 14y ago"But you should always choose to use native DOM methods if they are available to you." ...when you're writing code that has to run at 60fps. The rest of the time, you categorically should always be using jQuery. The native equivalent is very likely to be what jQuery is using under the bonnet, so jQuery is essentially just a wrapper most of the time. The performance hit from that wrapper is pretty close to zero. It's certainly nothing to worry about unless you're writing a game. The difference comes when jQuery isn't just a wrapper - likely for things where there are browser differences or performance improvements by doing things a different way. The majority of developers don't need to concern themselves with that sort of thing. We can just use jQuery and leave the performance 'hacks' to the jQuery team. Additionally to that, mixing native and jQuery code makes things trickier to manage, especially if you manage a team of developers who don't all work the same way all the time. "Just use jQuery" is a good rule-of-thumb. And lastly, jQuery has a vast pool of talent keeping up with browser tech better than you. Even the most avid follower of JS updates can't compete with a team of the standard jQuery draws upon. When a new method gets rolled in to the core of jQuery, something that speeds up selectors for example, your code improves without you doing any work. That'd a massive benefit. (How much of a jQuery fanboy am I?!)
- atirip 14y agoNot only games. Animations, dragging, building DOM - all are critcal situatons where every line counts, all benefit for close to metal code, every ms adds up.
- Jach 14y ago> every ms adds up Especially when any bloat is multiplied times however many visitors come to your site. Presenting an efficient front-end to your users is the polite thing to do, as it saves them both compute time and personal time. A lot of efficiency can be gained with tricks like removing dependencies, minimization through gzip, and ahead-of-time compiling.
- mistercow 14y ago>Especially when any bloat is multiplied times however many visitors come to your site Why would you multiply those?
- AndrewDucker 14y agoI'm curious - is there actually much overhead if your browser supports these native methods? Surely jQuery just goes straight to them? For anyone who knows jQuery internals, does it check for browser compatibility on every call, or does it check once, and then hardwire up the correct methods for the next call?
- ricardobeat 14y agojQuery has lots of feature checks, a long dependency tree, and a half-decade of accumulated bug reports and corner-cases. It also implements custom selectors and "fixes" behaviors in querySelectorAll that often leads to a significant drop in performance. Not that you'll notice unless you're using the DOM for rendering complex graphics/UI :)
- ivanca 14y agoFalse, any complex manipulation (graphic-less or not) of all DOM elements in the current page an you notice a significant performance cost in orders of magnitude.
- ghiculescu 14y agoA lot of the checks are done on initialisation. Take a look at jQuery.support - http://api.jquery.com/jQuery.support/ http://api.jquery.com/jQuery.support/ - it's around line 1300 in http://code.jquery.com/jquery-1.9.1.js http://code.jquery.com/jquery-1.9.1.js
- Schlaefer 14y agoRight from the source: "Sets document-related variables once based on the current document" [1]. It's a very readable document and the comments give good overview about quirks you have to be aware of. My personal opinion: not using jQuery (or similar library) for normal webpages is premature optimization and it will hurt more than help. [1] https://github.com/jquery/sizzle/blob/master/dist/sizzle.js#L489 https://github.com/jquery/sizzle/blob/master/dist/sizzle.js#...
- rorrr2 14y ago
- ricardobeat 14y agoNative APIs are the future, and everyone should learn to use them, but there are still too many gotchas and verbosity. Take a look at the code in rye.js[1], these are the most minimalistic wrappers to native APIs you'll ever get before ES6: https://github.com/ryejs/rye/blob/master/lib/manipulation.js https://github.com/ryejs/rye/blob/master/lib/manipulation.js This is what I expected jQuery 2.0 would attempt, and the shape most browser libraries will take in the not-so-distant future.
- mcbridematt 14y agoInteresting 'innerHTML' is mentioned as a crappy native equivalent. In theory, I agree. But last time I compared innerHTML vs DOM fragments, innerHTML was much much faster across the browsers I tried (this was just before JITs for JS became common place). The tradeoff it seems is the browsers native HTML parser and serialization vs holding a DOM tree in JS, and for large sets at least, innerHTML won handily.
- laughinghan 14y agoThat has been my experience as well, in fact, I believe the native DocumentFragment code should be slower than the jQuery innerHTML-based code.
- ivanca 14y agoIs not crappy because is slower, is crappy because it destroys all the eventListeners and custom properties of all their childNodes.
- brokenparser 14y agoIt's crappy because it's not just slow, it manages to freeze Firefox 22 on a 2,8GHz CPU. http://jsperf.com/leebrimelow-native-methods-jquery-dom http://jsperf.com/leebrimelow-native-methods-jquery-dom
- deleted 14y ago[deleted]
- ivanca 14y agoAt least we agree is crappy. BTW sorry for ruining your perfs, I really wanted to test some few things.
- brokenparser 14y agoOkay. Revision 9 adds code to remove the inserted elements, to put every test on equal footing. Is the practical equivalent yours? Because it hits a sweet spot.
- ivanca 14y agoFor the people saying "just use jQuery always, is not that much of a perfomance hit", is just blatantly false; any complex manipulation and you start seeing the difference right away; many times I have to use both, native selectors for performance but mixed with jQuery (for efficiency). Also, there are many scenarios where you can safely use things like querySelectorAll like browser extensions, WebGL apps, 2D canvas apps, (native) WebCam apps, WebRTC apps and many more. Furthermore, at this point is arguable how useful is to support IE8 and below. And this article falls very short of what can be achieved with the native implementation. For example thanks to JS being prototypical you can borrow almost any method from Array to your NodeList. [].filter.call(document.getElementsByTagName('a'), function(e){ return e.innerText === 'Brackets'; });
- laughinghan 14y agoTechnically not because JS is prototypical, but because of how ES5 defines `Array.prototype.filter`.
- ivanca 14y ago> Prototype-based programming is a style of object-oriented programming in which classes are not present, and behavior reuse (from Wikipedia)
- kibibu 14y ago> Furthermore, at this point is arguable how useful is to support IE8 and below I'm seeing this a lot, but IE8 is the highest "blue e that goes on the internet" on Windows XP. Its a brave (consumer-facing) business that can dump 10% of its customers [1] [1] http://gs.statcounter.com/#browser_version-ww-monthly-201305-201305-bar http://gs.statcounter.com/#browser_version-ww-monthly-201305...
- ivanca 14y agoIf you ask them to use another browser some of them will; so I argue is less than 10%. As a side-note "document.querySelectorAll" is supported by IE8, but unfortunately it doesn't have Array.prototype.filter nor other basic array methods.
- ceautery 14y agoNicely done... right up until the end: "In that world if your game doesn’t run at 60 FPS, you might as well go work at Target." Target made $69 billion dollars last year, and employs 365,000 people; I'd say there's no shame in working there. If the cushy software dev life leaves you unemployed at some point, and you need a working-class job to pay bills while you hunt for something more to your liking, how will you spin your snarky attitude to your interviewer?
- adventured 14y agoNothing like insulting a third of a million people in one sentence (and really millions more that work jobs even worse than a typical Target job).
- ezraroi 14y agoNice point.. i wasn't a ware that using the native selectors should give major performance impact. I will try to measure it and will see, Thanks
- stesch 14y agoEspecially setting newer CSS attributes is much better with jQuery. You'll miss some vendor prefixes for some browsers if you do it on your own. $('#foo').css('transform', 'rotate(5deg)'); No need to look up all the needed prefixes.
- ben336 14y agoI've seen a bunch of these noJQuery posts lately, but they've always focused on selectors. I'm curious what these people use for Ajax. Do they use the (very verbose) native syntax? Or are there any nice lighter weight libraries that separate out Ajax functionality into a readable abstraction like jQuery does?
- adventured 14y agoDefinitely a standard issue popularity backlash. See: PHP. Once something achieves overwhelming scale in tech, the majority turns on it because: dominance != cool.
- PavlovsCat 14y agoI use PHP without any shame, I even think MySQL might be just fine for me; but I also like raw JavaScript way too much to ever have bothered to use jQuery even once. That said, I have nothing against jQuery, but what used to annoy me was seeing Javascript questions being answered with jQuery snippets without anyone blinking, everywhere and all the time... you see, that's actually coming onto "my" turf and wantonly murdering there. That was too much, and if a "backlash" is needed to restore some sanity and balance, I say lash away.
- PavlovsCat 14y agoI like the part where someone else is making assumptions about anyone who isn't a jquery fan, I disagree based on the physical reality of my own existance, and some anonymous coward decides nah, I don't get to speak for myself, the one-sided blanket assumptions someone else pulled out of their ass are really all the "contribution" this "discussion" needs... oh well, thanks for the belly laugh ^^
- k3n 14y agoAre you thanking yourself for giving yourself a belly laugh?
- fvox13 14y agoMy job is to create web applications, not to keep track of every little idiosyncrasy in how various browsers have implemented core DOM methods. The jQuery team do a great job at keeping track of that stuff, and ensuring that things are consistent between different browsers. If I need something to be absolutely-blazingly-uncompromisingly fast I can use native methods, but for most people's use-cases, the performance hit you get with the abstraction is not sufficient enough to go back to using flint and steel to start a fire, after we invented the windproof lighter that is jQuery (or $FRAMEWORK).
- imjared 14y agoAuthor makes some points that are fine, I guess. A dev needs to carefully consider his audience and his fellow developers. If I can use jQuery and know that I'm not going to have cross-browser DOM API issues, then let me have it. Because the method simply doesn't work in older browsers (<IE8 http://caniuse.com/#search=queryselectorall http://caniuse.com/#search=queryselectorall) It's not entirely fair to say that `$(".my-class li:first-child")` is equal to `document.querySelectorAll(".my-class li:first-child")` or that `$('.my-class')` is equivalent to `document.getElementsByClassName('my-class')` (doesn't work in <IE9 http://caniuse.com/#search=getelementsbyclassname http://caniuse.com/#search=getelementsbyclassname). If you're building games or working with a team who does, I'm going to guess you're working with fairly edge functionality in browsers where javascript support is great. If you're building sites for clients who are still (sigh) using IE7 internally, you just can't get away with something quite so simple. As another commenter mentioned: "Even the most avid follower of JS updates can't compete with a team of the standard jQuery draws upon. When a new method gets rolled in to the core of jQuery, something that speeds up selectors for example, your code improves without you doing any work." This is the same reason I use a library for preprocessing my CSS. I'd rather update a gem and trust a team whose focus is processing CSS than try to rely on myself for keeping up to date with the pace of the CSS WG and browser vendors. Also, for anyone wanting to dig around the jQuery source, James Padolsey made a great tool for it. I know I was pretty amazed to find out just how much is going on under the hood. http://james.padolsey.com/jquery/#v=git&fn= http://james.padolsey.com/jquery/#v=git&fn=
- jamesaguilar 14y agoWhat I'm curious about is, if these are equivalent, why doesn't JQuery just delegate to them in browsers where it is supported? Then you can get both the speed and the compatibility.
- mambodog 14y agoIn the case of querySelectorAll, it does[1] (after performing some checks for easy wins) and if this test[2] is anything to go by, it can actually perform better in some cases. [1] https://github.com/jquery/sizzle/blob/master/sizzle.js#L237 https://github.com/jquery/sizzle/blob/master/sizzle.js#L237 [2] http://jsperf.com/yui3-vs-jquery-selector-test-3/54 http://jsperf.com/yui3-vs-jquery-selector-test-3/54
- QEDturtles 14y agojQuery is a pleasure to use. It's just plain useful. If you need to manipulate the DOM in legacy IE, nothing compares. I'm reading a lot of complaints about the overhead for legacy IE support (presumably from people with better clients than mine...) but I'm surprised no one has mentioned Zepto. I haven't had a chance to use it yet, but isn't it just a stand in for jQuery where legacy support gets stripped out? I'd love to see the benchmarks.
- brokenparser 14y agoNo, that's jQuery 2.0. Also, Zepto is slower.
- jak1192 14y agoGreat article. Newer developers are spoiled by jQuery and don't realize that all it does is make native javascript a bit cleaner. However, one nightmare javascript task that this article overlooks is ajax. Native javascript ajax is no where near as simple without jquery
- just2n 14y agoCool article. I'm a big fan of noQuery. One thing you could improve is regarding appending, using insertAdjacentHTML instead of constructing the DOM manually in a document fragment. It's significantly less code and should perform better.