18 ms·
You might not need jQuery
- lowglow 13y agoMakes me think of: http://vanilla-js.com/ http://vanilla-js.com/
- bitwarrior 13y agoI understand the desire for people to make pages like this (this isn't the first), but the examples are not completely honest with themselves, in my opinion. One of the biggest benefits jQuery introduces is the concept of treating single selections and multiple selections identically. While using jQuery, I can emit a $(".class").hide() call, which will apply to all elements with the matching class. Simple and elegant. However, using native JS as the page suggests, I will need to construct a loop within my function, especially if I'm using the DOM supported getElementsByClassName method, returns a pseudo-array of DOM nodes which don't have the style method available on them. You'll notice the examples already assume a selected element and leave much of this heavy lifting out. Furthermore, jQuery offers the selection simplicities of Sizzle (ie: "#div .container .item). To do the same selection process in vanilla JS, I'll need to nest 2 getElementsByClassName functions in a getElementByID function, and return the concatenated results from each potential .container. That is to say nothing of more complex selectors. So yes, if you're addressing the absolute simplest form of selection, this works, but otherwise I don't think it's really presenting the situation honestly.
- sfeng 13y agoThis is actually a great example of the purpose of the site. Since IE8, browsers have supported a native 'sizzle-style' element querying syntax: http://youmightnotneedjquery.com/#finding_elements http://youmightnotneedjquery.com/#finding_elements IE9 and later also support a native each. You are correct however that you'd have to use Array.prototype.each.call, because the NodeList is not a real array.
- exizt88 13y agoResig on document.querySelectorAll: http://ejohn.org/blog/thoughts-on-queryselectorall/ http://ejohn.org/blog/thoughts-on-queryselectorall/ Good SO discussion on this topic: http://stackoverflow.com/questions/11503534/jquery-vs-document-queryselectorall http://stackoverflow.com/questions/11503534/jquery-vs-docume...
- tghw 13y agoIt's still more complex, because you still have to iterate over it.
- ordinary 13y agoIt sounds like you're looking for the querySelector and querySelectorAll methods: https://developer.mozilla.org/en-US/docs/Web/API/Document.querySelector https://developer.mozilla.org/en-US/docs/Web/API/Document.qu...
- wwweston 13y agoquerySelector and querySelectorAll could have been pretty great, but they suffer from some serious problems as they ended up spec'd. The one I hate most is that qSA returns Yet Another JavaScript Collection That Is A Lot Like An Array But Isn't An Array And Therefore Doesn't Have Any Of The Nice Methods(TM). Yes, you're going to have to iterate over the thing using an index in a loop. There's others: http://ejohn.org/blog/thoughts-on-queryselectorall/ http://ejohn.org/blog/thoughts-on-queryselectorall/ I'm really not sure how the standards-makers got this so terribly wrong given that the libraries had already started to solve the problem.
- hawkharris 13y agoYou can count on one hand the number of jQuery features that most developers incorporate into their projects. E.g.: - Setting or getting css attributes - Querying the DOM - Manipulating and walking through arrays Each of these features can be replicated with fewer than 10 lines of code.
- shittyanalogy 13y agoChaining and implicit iterators.
- sfeng 13y agoSince I've started using an MVC, I use chaining less and less. I tend to just use a variable the few times I need to do a bunch of manipulation to the same element. Beyond that, any chain using .end is nuts to me.
- caiob 13y agohttps://cloudup.com/cSLcmVC5F9h https://cloudup.com/cSLcmVC5F9h <--- Def not a good example. hehe Great website, though.
- maresca 13y agoThere are many things you don't need to do. I'll take the time saved in development over cutting out an extra framework.
- sfeng 13y agoLike it says at the top of that page: > jQuery and its cousins are great, and by all means use them if it makes it easier to develop your application.
- rfnslyr 13y agoYeah, I don't have to wear shoes outside, but the alternative is very destroyed and useless feet. Maintaining my boots is far less work than curing my hurt feet.
- eli 13y ago> in truth, post-IE8, browsers are pretty easy to deal with on their own I totally agree, but not everyone lives in a post-IE8 world. It's as much as 10% of our traffic on some sites and several big clients use it.
- afschwartz 13y agoThat's why it's called You_Might_NotNeedJQuery. ;)
- badman_ting 13y agoWould be great if we could all stop recapitulating this, it's not helping
- VintageCool 13y agoIf you are developing a library, then your users _Might_ need to support old browsers and _Might_ need jQuery.
- hamburglar 13y agoIt's hard to tell if this site is advocating for ditching this type of js library altogether and writing all those replacements inline (ick for some of those) or simply replacing jQuery with a thinner (and narrower) library. I could be convinced of the latter but not the former.
- sfeng 13y agoI think that what it's saying is that you can write yourself a microlibrary that just includes the ten or fifteen lines of adapter code you actually need for the thing you're building, and that you should use native browser constructs whenever possible.
- afschwartz 13y agoOne of the main things we're advocating is to consider not depending on jQuery when building an open-source project. For Offline, PACE, Odometer, Tether, and many of our other OS projects (http://github.hubspot.com http://github.hubspot.com), we chose not to depend on jQuery because it means our libraries can be smaller and more people can use them. We're happy and proud to use jQuery when building an application. As many other commenters have noticed, it can be extremely useful at reducing code complexity—and let's just say it: it can make it more enjoyable to write front-end code!
- kmfrk 13y agoWhat's a good resource to read up on how browsers handle unsupported JS, if I want to write a fall-back? I've already got fall-back for people who've turned off JS, but I've yet to write anything for unsupported JS.
- eli 13y agoThis might be overkill for you, but take a look at http://modernizr.com/ http://modernizr.com/ Sometimes it's just as simple as testing if the function your about to call exists before you call it.
- exizt88 13y agoWhat? > $('<div>').append($(el).clone()).html() vs > el.outerHTML Why not $(el)[0].outerHTML?
- phaed 13y agoYou had me convinced until I scrolled down to read the code examples and realized why I actually do need jQuery. If its between adding yet another collection of utility functions to approximate the functionality jQuery would give me vs just adding jQuery. I'd rather go with jQuery.
- sfeng 13y agoOne way of looking at it is that if you already have underscore to give you _.extend and the like, you can get pretty far with just what the browser gives you.
- VMG 13y agoThe first example alone is reason enough to use jQuery - why would I want to use four statements instead one? Why would I want to have to remember to call `send`? Why do I have to remember the last boolean parameter of `open`?
- sfeng 13y agoTotally valid, but just to say, jQuery's API is just as arbitrary, you just happen to know it better. If you use the native XHR a couple times, you know what open's parameters are.
- alxndr 13y agoIt is just as arbitrary, but I feel jQuery's API is also easier to grok at a glance. Using either a couple times may instill the parameters in your memory, but what about coming back to it after six months?
- ufo 13y agoIf you are writing a library, eliminating a dependency is worth much more then 4 lines of code. But yeah, if you are just writing code for your own site then knock yourself out.
- vinceguidry 13y agoWhich javascript library are you developing?
- mike-- 13y agoIn my opinion jquery is a hell. Because jquery is only abstraction for browser features level (events, styles, dom), but it's ugly for writen complete code, for this need some like prototype.js or mootools, because it's have oop-style level for browser.
- jsnk 13y ago"You might not need Ruby on Rails. Use C to rewrite tons of shit you need." Use jQuery please. Rewriting jQuery methods with vanilla js usually turns out to be a hack job that is buggy and ugly. Just use jQuery.
- sfeng 13y agoThis is exactly what we're trying to combat. For modern browsers, in many cases, it's just not true. There are a few utility methods that are tricky to replace, but you really shouldn't be including jQuery only for it's utility methods.
- thothamon 13y agojQuery provides a uniform API that is guaranteed to work on supported browsers. The jQuery team does all the work to back that guarantee. If I rely on raw JS, then I'm one glitchy browser implementation away from being broken. Even worse: suppose you build a product with the approach you recommend, it's very successful, and then your sales team makes a major sale to a stodgy old bank that still uses IE7. Or maybe you just never make the sale because you don't support the browser they use. OK, let's say we should all turn away money from IE7 users because it's insecure and old. For OP's strategy to work, we have to assume all browsers we care about will be compatible going forward. I think this is a very unsafe assumption to make. While one small incompatibility would only be a minor annoyance, once you have more than a handful of these, a compatibility layer like jQuery again looks very nice. And none of this even speaks to the fact that the jQuery implementation in the source article is generally at least as short and readable as the alternative, or that most people are more familiar with the jQuery version. The only reason I can think of for dumping jQuery is maybe speed optimization, and even in that case, well-implemented jQuery should be no slower than the native speed plus the cost of a function call. If it's slow and you want to optimize something, why not optimize/bug-fix jQuery itself and help everyone, not just your one project?
- aroman 13y agoThat's a really bad analogy. People don't use Ruby because C's standard library works differently across different platforms. This isn't about "rewriting jQuery methods with vanilla js". It's about using the built-in, native, vastly more performant methods that come standard on modern browsers.
- leobelle 13y agoquerySelector and querySelectorAll have bugs in IE8. Checkout the jQuery source code and search for these functions and see the comments and workarounds if you want to be sure: http://code.jquery.com/jquery-1.11.0.js http://code.jquery.com/jquery-1.11.0.js Notice the rbuggyQSA variable. Also check out Quirksmode: http://quirksmode.org/dom/core/ http://quirksmode.org/dom/core/
- neduma 13y agoAwesome site with clear message. +1
- exizt88 13y agoSo, uh, what will I gain by ditching jQuery? I will lose a beautiful API with a simple, terse and familiar syntax. I will have to work with an ugly, inconsistent and loquacious API, which has no guarantee of being cross-browser (or accounting for various browser quirks). And for what? I doubt 81 KB would make much difference to 99.9% of my visitors. As for performance -- it makes sense to rewrite bottlenecks in pure highly-optimized JS. But to write vanilla JS from scratch, without even knowing whether you'd need that performance boost is a pure waste of time. UPD: it has been pointed out that this webpage is directed at developers of JS libraries. In this case, all these points are valid, but the title, then, seems to be either misleading (as in "link-bait" misleading) or a plain truism.
- JacksonGariety 13y agoYou lose dependency on a monolithic library which creates vertically-stacking dependencies and library conflicts. By ditching it, you gain the ability to construct your app out of loosely-bound components supported by independent developers.
- exizt88 13y agoCould you elaborate on how jQuery creates vertically-stacking dependencies and library conflicts by itself?
- michaelt 13y agoObviously, you cannot have dependency conflicts if you only have a single dependency! We need a slightly more complicated example to understand the problem. Let's say I'm making the new customer checkout page for my startup. I decide to call an e-mail address verification as a service API, their library uses jquery 1.8 I decide to call an address verification as a service API, their library uses jquery 1.11 I decide to call a credit card validation as a service API, their library uses jquery 2.0 You go to the e-mail address verification company and say "Do you have a version that supports a newer version of jquery" and they say "yes, also we redesigned our library's interface so if you upgrade you'll have to change all your code..."
- deliminator 13y agoMy colleagues and I learnt that lesson the hard way. We are working on a WYSIWYG editor (Aloha-Editor) and the first version did depend on jQuery (and jQuery UI for that matter). That caused a lot of trouble for people integrating the editor in their websites, especially if they were already using jQuery. For our particular case we really didn't need it, as it's just as easy to say .getAttribute() instead of .attr(), and we didn't use selectors much, if at all. Effort is underway to get rid of the dependency from the core library in the next major release.
- hartator 13y agoIt's odd, but after reading everything and the examples at the end, I feel we need jQuery more than ever. Kind the opposite of the OP is stating. Great post though.
- padseeker 13y agogreat content, terrible opinion. I like your take on the article.
- justinph 13y agoYou might not need jQuery 1.x. You might be able to use jQuery 2.x instead, which is smaller, faster, and drops support for IE8 and below.
- nostrademons 13y agoCouple improvements to some of the modern-browser code examples: FadeIn: element.style.transition = 'opacity 400ms ease-in-out'; element.style.opacity = 1; Each & filter (this also applies to people's complaints about browser methods not working on collections): [].forEach.call(document.querySelectorAll(selector), function(el) { ... }) The native versions also usually run several times faster than the JQuery versions, which is the main reason to use them. This meme that you can't build performant, jank-free HTML5 mobile apps? It's largely because of JS libraries and developers that don't know which operations are fast and which are slow. I'll also plug my colleague's autogenerated index of the HTML5 APIs: http://html5index.org/ http://html5index.org/
- leobelle 13y agoI've had pretty terrible performance with complicated CSS animations that I managed to clear up with switching to JavaScript and requestAnimationFrame
- nostrademons 13y agoAre you animating the transform/opacity properties and only those? That's the general secret to smooth animations on web - they're GPU accelerated, everything else requires a call into the browser's layout engine on every frame.
- gisenberg 13y agoTransitions didn't end up being supported until IE10, which wouldn't jive with the IE8+ baseline the site proposes.
- sdegutis 13y agoI wondered to myself, why did he create a custom website just to present this? It seems like a great way to position yourself as a skilled front-end developer and advertise your services to potential clients. I suppose it could also have been done out of some kind of altruism, but I'm guessing the former. Either way, this is pretty neat, and I'll probably be bookmarking it. We're using ClojureScript now and migrating away from jQuery, so this may prove handy.
- drawkbox 13y agoIndeed you don't need jQuery. Though, there are standards and there are market/industry standards. jQuery has become a market standard wrapper. If jQuery isn't used, developers will still write a wrapper to ease some of these methods. It is better if that is a common market standard like jQuery than everyone doing it. The amazing part of jQuery still to this day, beyond the selectors (which can now be replaced yes), is the plugin system. Just like Python, there is a plugin for everything and if you don't like them or there isn't one, developers can easily make one and share it with the world and it just works (tm). It is the most easily pluggable javascript library. It creates a baseplane that developers can be more efficient in. Everybody tries to replace the jQuery selectors, animation etc but they miss that jQuery is a platform and a pluggable one at that. It is responsible for tons of productivity.
- sheetjs 13y agoGreenspun's Tenth, updated for 2014: "Any sufficiently complicated website contains an ad-hoc, informally-specified bug-ridden slow implementation of half of jQuery" I understand the visceral opposition, but once you start writing a fallback to support some browser (something to support IE or FF or Safari or Chrome ...) you might as well use the battle-tested solution (and write your own thing if you find performance to be unacceptable and trace the bottleneck to jQuery)
- sfeng 13y agoThe question at hand is, are fallbacks necessary anymore for the browsers we are targeting today?
- __david__ 13y agoAnd the followup is, when do you remove fallbacks from your code? Every time I think I should remove something I end up thinking, "well, it still works just fine, does it really matter if it stays for a little longer?"
- nostrademons 13y agoThe cost is in latency and complexity for users of your head browsers. How much do you want to reduce the user experience of your users on modern browsers to support users on old ones? There isn't a one-size-fits-all answer for this, but you should have some idea of what your traffic breakdown by browser is, and ideally what your cost in conversion rate is for each additional ms of latency (this varies by industry). I don't remember offhand what the cost per byte in latency is, but IIRC we measured something like 1ms per 1K bytes at Google (this would work out to a 1 MBps = 10Mbps connection, which seems around right for typical cable/residential fiber households these days).
- __david__ 13y agoI'm not sure what you mean about "complexity for users of your head browsers". The idea of the fallback/polyfill is that it doesn't even come into effect for the modern browsers. As far as latency is concerned, I hear you and that makes sense, but the things I'm talking about are not very big, so the latency gain isn't going to matter much for our purposes. Yeah, we definitely look at the analytics. But even if it the old browser users are sub 1 percentage point, I see the number and think, "I could take this 5 line polyfill out, but then these 1000 uniques wouldn't work." And I just don't have the heart...
- polemic 13y agoThis be right on a purist level, but on every practical level there is little reason not to use [library of your choice]. If you're loading from the google/jQuery CDN (with suitable fallback, obvs.) you've got a good chance of a cache hit, and even if it misses it's a tiny one-off penalty. And ultimately, why not? jQuery works, has a wide base of users, etc. Sure your trivial Js might not need jQuery features now, but as you add more dynamic behaviour, at some point you'll wish you had just used it to begin with. A better message might be: make sure you know what the underlying javascript looks like, because there are a lot of people helpless without jQuery. PLUG: if you're bored of jQuery, try Dojo. Far more power, in a less intrusive form, IMO.
- fat0wl 13y agoi do Enterprise work & if we have jQuery in a page IBM dismisses our PMRs when we submit issues. So yeah I regularly include some simple cross-browser-normalizing js functions to use with the vendor-approved libs. Also, jQuery is not trival to use in conjunction with other js libs (Dojo) as namespacing proponents claim. It's not like you just include both & they don't interfere. You have to follow a specific initialization pattern.
- polemic 13y agoI don't understand this comment - I'm not suggesting you should use jQuery or nothing, or jQuery and Dojo. My point is the reasons given in the post for not using a DOM library of some sort are not valid.
- fat0wl 13y agoo ok i was taking your comment within the context of the post -- more like "why not allow jQuery as a dependency for an open source lib". sorry for misread
- danielweber 13y agoIsn't it a giant security hole to be loading part of your library from another site you don't control? Zillions of people do it anyway, so it's not like you won't have lots of company.
- chavesn 13y agoThe Bad: The premise of the examples list seems a bit disingenuous. Very few of these things take into account the full convenience of jQuery. It's much more than saving a couple lines of code or knowing the native way to accomplish the most basic version of a task. jQuery's real benefit is preserving simplicity as your needs grow more complex. Right off the bat I feel like the getJSON[1] example is a bit simplistic. Almost anyone using ajax needs to serialize data, handle errors, prevent caching, etc. jQuery has thought about all this[2]. Don't get me wrong -- most of my work has been without jQuery, but that means I know exactly how much work it is. The Good: The format is a nice way to show people (who really don't know otherwise) the native JS plumbing. "The number of people who don't know that jQuery != Javascript is too damn high". So to help combat that, I really appreciate the idea behind this site. It's great to show side-by-side how jQuery isn't "magic", since many people seem to learn jQuery these days without even knowing the first thing about Javascript, but I just think it should be presented with a slightly different premise. [1]: http://youmightnotneedjquery.com/#json http://youmightnotneedjquery.com/#json -- side note, why did they set the handler after the `send`? It seems like that could cause problems if the result was returnable quickly, such as from cache, though I haven't tested it. [2]: http://api.jquery.com/jQuery.ajax/#jQuery-ajax-settings http://api.jquery.com/jQuery.ajax/#jQuery-ajax-settings
- ep103 13y agoright off the bat its wrong, IE8 doesn't include JSON support unless you're in strict mode.
- cozuya 13y agoThanks for traversing the bounds of space and time and posting this blog post from the year 2018 when IE8 is no longer supported for enterprise.
- sfeng 13y agoIt will still be here when the world is ready
- mortenjorck 13y agodocument.title.replace(“You”,”Your JS library”);
- efuquen 13y agoNo, please no. If size is an issue for some reason or you want to have no dependencies you can use something like http://zeptojs.com/ http://zeptojs.com/ and just embed everything in one minified file. If you do things right only the functions you are actually using will get placed in there as well. Do not reinvent the wheel to solve problems that can't be solved in much cleaner and nicer ways. Managing dependencies can be annoying, but we all bite the bullet for a very good reason, because reusing solid well tested code is a good thing.
- napolux 13y ago100% agree!
- chavesn 13y agoFantastic point. Abstractions can be dangerous because they often aren't developed right. But that isn't the case here. When something like jQuery comes along, hiding so many gory details, and has been tested to death both in development and in production use all over the world, we are all better off because we remove so much failure surface area from our code.
- sfeng 13y agoThe question is, how many of those gory details still exist in modern browsers? There's not much to test if you're just calling el.classList.add().
- JacksonGariety 13y agoThe important part of ditching jQuery isn't the load time, it's aiding the transition from monolithic libraries to loosely-bound components.
- zertosh 13y agoArticles like this miss the _true_ genius of jQuery – that it basically wraps all DOM operations in a maybe monad. You get null safety for free.
- sfeng 13y agoOne could ask if that's actually a good thing. You also get the same thing from the existential operator in coffeescript, if you're in to that.
- nfoz 13y agoI should probably register pleasedontusejavascript.com
- abus 13y agoPlease can we embed jQuery in browsers instead of the standard being to use Google's hosted copy.
- um304 13y agoI would still stick with jQuery because it lets me achieve more by writing less. Out of many things, just see triggering custom events. It'd be horrible if I'll have to write that piece of code again and again and make sure it's bug-free. And if I contain that long logic into a function for re-use, and use this approach for everything listed on the page, I'll end up writing my own library that I'll be including in each of my projects. Wait, why don't I use jQuery instead which is battle proven and better tested than my library ever will be?
- Bahamut 13y agoSome of the examples are flawed. The ajax one for IE8+ is a big red flag, it's not as easy as that. However, operating in the world without jQuery is scary for a new developer. I think it has its utility. Note: I tend to prefer not to use jQuery, especially with AngularJS around. YMMV
- coldcode 13y agoSometimes doing it yourself makes sense. But most often using a well tested battle hardened tool is better. I rarely if ever build my own car.
- emehrkay 13y agoI've never liked jQuery. I use it because I am forced to. However, I will not write my own animation library, selector engine, and other helper utilities it provides.
- nostrademons 13y agoYou don't have to. Browser manufacturers wrote an animation library (CSS3 transitions & animations), selector engine (querySelectorAll) and other helper utilities it provides.
- jbeja 13y agoI would glad to see a youmightneedclojurescript.com.
- rubysucks 13y agoGreat, get the hipsters to make their own javascript. Haven't you guys ever maintained an existing code base? Using a "custom" framework that some kid thought up, in any language, is a nightmare. http://seven-degrees-of-freedom.blogspot.com/2011/01/job-security-through-code-obscurity.html http://seven-degrees-of-freedom.blogspot.com/2011/01/job-sec...
- superlupo 13y agoRecently, I have developed a small page where I wanted not to use jQuery on purpose and code against the DOM APIs instead. For IE8 compatibility I have used [1] (so I could use addEventListener and DOMContentLoaded for example), and also shims for ES5 [2] (e.g. Array.prototype.forEach) and classList [3]. While I did not run in any troubles, I don't think it is worth the effort, alone just because jQuery has a much nicer and shorter API (cp. ".on()" vs. ".addEventListener()"). But I still support the case that not every plugin/library developer should depend on jQuery by default, even if it is not necessary. [1] https://github.com/WebReflection/ie8 https://github.com/WebReflection/ie8 [2] https://github.com/es-shims/es5-shim https://github.com/es-shims/es5-shim [3] https://github.com/eligrey/classList.js https://github.com/eligrey/classList.js
- windsurfer 13y agoYou might need some semi-colons though... http://robertnyman.com/2008/10/16/beware-of-javascript-semicolon-insertion/ http://robertnyman.com/2008/10/16/beware-of-javascript-semic...
- ateevchopra 13y agoI don't know if i need jQuery or not But your page is seriously a great "Cheat Sheet" for all jQuery Learners out there ! Thanks
- rwaldron 13y agoMy favorite part is how I learned that I don't need to use `var`—I can make everything global!!
- notJim 13y agoI recently did a project that didn't use jQuery in order to keep my code smaller. It was an embedded 3rd-party widget, so keeping the code as small as possible was a key requirement. The code I wrote supports down to IE7, but IE7 wasn't really the biggest issue. The real problem with not using jQuery is that all of the collective knowledge we have about browser inconsistencies is encapsulated in jQuery. When you run into this, and Google it, you'll find a million StackOverflow answers telling you to use jQuery, and if you get lucky a blog post from 2007 that actually answers your question. The result is that you end up spending time reverse-engineering jQuery to get your thing working. To be clear, in my case the tradeoff was worth it (the code for my entire widget including the bits of library I had to write is smaller than jQuery), but it's not a tradeoff I would make unless I had a good reason.
- nostrademons 13y agohttp://caniuse.com/ http://caniuse.com/
- gisenberg 13y agoNot sure what you're getting at. Feature support doesn't mean there aren't inconsistencies in implementation, and caniuse's documentation on that delta are very much surface-level.
- Arnor 13y agoI don't understand why so many comments here seem to have skipped over the word "might" and the entire introduction. The point isn't stop using jQuery. The point isn't even don't ever use jQuery for plugins. It's simply that if you're only using a couple features of jQuery, consider eliminating the dependency. Why is there so much backlash to that?
- jchrisa 13y agoThis is a great resource, even though it's not really about jQuery, it's about the success of HTML5. The fact that we have a working DOM, XHR, and a better understanding of polyfills in general does tip the balance away from depending on a "fix it" library. I can see myself reaching for this page a lot. And the author has a point as the only reason I used Zepto on my last project was one of the libraries I needed used it. If I am gonna use a fix it library today, it's more about nodejs/browser compatibility than worrying about browser issues.
- ests 13y agoOr in other words: YMNNJQ
- dudus 13y agoDOMContentLoaded doesn't even get close to the jQuery counterpart $(document).ready. To start if the DOM is already loaded DOMContentLoaded won't fire and won't call the callback. On the other hand ready will notice that the DOM is loaded and fire the CB right away.
- trevorhartman 13y agojQuery or <jQuery-compatible substitute> is one of the few things I don't have to think twice about before including in EVERY WEB PROJECT I EVER WORK ON before doing anything else. Next up: you might not need <insert abstraction>. Really?! What does "need" mean? Go write assembly.
- rwaldron 13y ago<3 lol
- acconrad 13y agoI'm psyched by the idea that you don't need a bloated framework, but between using Zepto as an alternative, as well as the fact that some of this information is just plain wrong (e.g. they claim that the classList API is supported by IE8+, when in fact it is only supported by IE10+), this won't get you too far.
- 6thSigma 13y agoI don't get it. From the examples it seems that the jquery way of implementing things is much easier and more concise. Isn't that the entire point of a library?
- k_bx 13y agoIn first example: > data = JSON.parse(request.responseText) Maybe "var data = ..."?
- padseeker 13y agoI use jQuery because the DOM API for javascript sucks, and writing jQuery is fun. You're average web app perhaps doesn't need the latest Ruby/Python/PHP framework, or perhaps it you can write it without the framework. Or perhaps you can a compiled as opposed to interpreted language because that would be faster. OR maybe you can use something that is even faster, like perhaps Assembler! Fuck it write machine code if speed is the most important thing. Do you know why you don't? Cause writing Assembler or machine code sucks. You lose very little in load time by including a minified version of jQuery, while you gain an enormous amount of ease of use and readability. Also it'll be more fun. Just include the jQuery and be done with it.
- ubernostrum 13y agoI use jQuery because the DOM API for javascript sucks, and writing jQuery is fun. How many lines of code are actually needed to give you selectors and the most common DOM manipulations? How many lines of code are in jQuery? Is there anything which would not be in selectors + common manipulations that you need, and which only jQuery can provide?
- padseeker 13y agoDOM selectors and events are critical, maybe ajax. Perhaps you could pare it down a bit - I don't need the animation stuff. I have no idea what the size using only what I might need when I needed it. But then that becomes a whole another endeavor - how much load time will be saved by only using the parts you need, and how long will it take to figure out what you need and what you dont? It's all about return on investment. What do I need now, what won't I ever use, and what might I use later. It becomes more work to save, what, 1/4 second? Maybe a bit more on mobile. It isn't worth the trouble. The whole obsession over the load time of jquery feels like an exercise in OCD.
- npongracic 13y agoI think this is great, i was also thinking of replacing jquery functionality in some of my scripts with native methods and this helps me alot. One question though, what is the pure javascript equivalent of $(document).on('click', '.selector', function() { // do something }); This is the new jquery .live() replacement and i need it because normal events stop working after async postbacks (eg. from an asp.net UpdatePanel). Will this code do the trick if i attach it to the document element? Also i need IE8+ support :) function addEventListener(el, eventName, handler) { if (el.addEventListener) el.addEventListener(eventName, handler) else el.attachEvent('on' + eventName, handler) } addEventListener(el, eventName, handler)
- achairapart 13y agoI feel empathy for the OP, for two main reasons: 1) The fact that some people don't realize that JavaScript != jQuery scares me. 2) jQuery born when cross-browser compatibility was a mess and today it still carries that weight. I think nowadays it needs to be more modular and less monolithic.
- camus2 13y ago> 1) The fact that some people don't realize that JavaScript != jQuery scares me. DOM != Javascript That's the thing you dont understand and makes you say silly things.
- iagooar 13y agoI would like to add a thought about the dispute about the need of using jQuery. Let's say we know a consultant, let's call him Bob, who works on client projects. He needs to implement new features fast, and does not want to worry about low level stuff. Once he's done with a project, he moves on to another. Then, we meet a JS-framework developer, let's call her Alice. She has to weight every line of code she writes because her decision can have have a huge impact on thousand of developers using her stuff. She needs to understand a lot of low-level details in order to make good decisions and ship rock solid stuff. Now, both Bob and Alice have to decide whether they need to include jQuery in their projects or not. Heck, they need to justify their decisions to their teams / managers. What's Bob going to say? He will start thinking about what will happen if he does not include jQuery to his project. Well, he will have to implement some of the low-level stuff by himself, and later maintain the code. Probably, in a month he's going to be working on another project and will have to copy & paste the same stuff over. And if there was a bug? Is he going to update all the previous projects he is not getting paid for anymore? If he's smart, he's going to say: we'll take jQuery, as it provides a nice, stable, robust and battle-hardened API. We're going to move faster if we use it, as we don't want to reinvent the wheel. What about Alice? She will probably have to consider introducing a new dependency to her framework. Is it OK to add those additional hundreds of lines of jQuery code to an already large codebase? Is she going to be able to provide a consistent experience between different (and future) versions of jQuery? Is the core of her application going to rely on an external tool, even if it is rock-solid and lose the potential to make low-level optimizations and have full control? Maybe, she's going to say: well, I'm going to identify the elements that need some of jQuery's stuff and implement it by myself. She will be taking the time and effort needed to test it well and be sure that it works across different platforms. At the end of the day, both will have made the right decision, even if in absolute terms they took the exact opposite action. Software engineering is about making decisions, in a given context and moment, for a given purpose. As software engineers, we should not generalize about some of the decisions people have to make. There is no one single truth, it all depends on a variety of variables and factors. Let's be Bob and Alice, be smart and make the best decisions for our projects.
- lotyrin 13y agoThank you. Its astounding how much of this thread does not seem to be catching this. My project currently depends on libraries which in turn have dependencies on mutually exclusive versions of jQuery, so we conditionally load a whole second copy some of the time. I've been meaning to fix the libraries that require older jQuery so we can fix this, but the bugs run deep, the libraries are pretty unmaintainable, and I'm under pressure to keep shipping features.
- LukeHoersten 13y agoIt'd be cool if you could search a URL and it would analyse whether you need JQuery or not.
- Gonzih 13y agoWell... I don't like this trend. I saw project once where main frontend guy decided to do stuff without jquery and etc. He said that vanilla.js is nice and people just don't get it. After project was done it worked only in firefox properly. Lot of time was spend after that to implement fixes for different browsers. So don't do that. Don't use vanilla js. Size of jquery is issues? Well you are trying to solve problem that does not exist.
- deleted 13y ago[deleted]
- pacomerh 13y agoI think many commenters are misunderstanding the main idea here. This page makes a strong case if you're just using jQuery for a few things in your site. I can see people complaining "why would I write all that code again? if jQuery offers a beautiful API?" if you're just using jQuery to do a few simple things (Which I've seen all over the place among peers) then why not just write the native version? it's only a few lines and you're saving a whole library in your load process
- dsego 13y agoShouldn't you set request.onload before calling request.send?
- leterter 13y agoAngularJS is all you need.
- lignuist 13y agoCiting the AngularJS FAQs: Does Angular use the jQuery library? Yes, Angular can use jQuery if it's present in your app when the application is being bootstrapped. If jQuery is not present in your script path, Angular falls back to its own implementation of the subset of jQuery that we call jQLite. Due to a change to use on()/off() rather than bind()/unbind(), Angular 1.2 only operates with jQuery 1.7.1 or above. http://docs.angularjs.org/misc/faq http://docs.angularjs.org/misc/faq
- at-fates-hands 13y agoThis is fascinating to me since I'm already moving away from jQuery. I'm always looking for other ways to do what many people use jQuery for. For example, I'm now using CSS3 animations and transitions instead of jQuery. I've also started using Angular.js quite a bit and have found most of the time, it requires less code than jQuery. It also has its own subset of jQuery "jqLite" which has a much smaller footprint so your app doesn't need to rely on that jQuery dependency.
- Fizzadar 13y agojQuery still has it's uses... like when it's essential to have consistent support across browsers old & new. However I much prefer to tell users who insist on using out-of-date/poorly-built browsers to upgrade or fuck off, hopefully gently encouraging them to do so.
- chenster 13y agoIf you only care about IE such as inside corporate intranet, and never had to worry about cross browser compatibility, knock yourself out. On the other hand, the scalablity and performance on the intranet usually are not a high priority. Why not just learn jQuery rather than tight yourself up to vender specific, proprietary technology?
- ivanca 13y ago>post-IE8, browsers are pretty easy to deal with on their own. False: - CSS browser prefixes are automatically inserted by jQuery - Many jQuery selectors don't exist in the CSS selector specification - Looks really really ugly and that makes it hard to read for you and other coders. var pairs = $(".form").not(".old").serialize(); /* without jQuery */ var pairs = [].slice.call(document.querySelectorAll(".form")); var data = forms.filter(function(ele){ return /\bold\b/.test(ele.className); }).map(function(ele){ var form = ele.querySelectorAll("select, input, textarea"); var pairs = [].slice.call(form).map(function(subele){ // maybe if subele.type === "select" // but I got tired of writing this example // but that's the point anyway return subele.name + ":" + (subele.value || "") + ";"; }); return pairs }).join("").replace(/;$/, ""); So be kind with your co-workers, use jQuery. Even my 5 year old android can run jQuery without freezing the built-in browser.
- BESebastian 13y ago> Looks really really ugly and that makes it hard to read for you and other coders. This point might have been better made if you hadn't intentionally structured it to be as unreadable as possible, and also shoved in a few lines of comments to pad it out and make it look bigger than it needs to be. Not a very honest example at all, considering native JS can be as readable as you want to make it. > So be kind with your co-workers, use jQuery. Even my 5 year old android can run jQuery without freezing the built-in browser. My co-workers can read and write native JS with or without jQuery as it is, why is it being _kind_ to avoid writing in the style of the native language?
- ivanca 13y agoExpressiveness means you waste less of people's time and mental effort. $(".enemy").after('<div class="crash">').remove() Without jQuery: var enemies = document.querySelectorAll(".enemy") for (var i = 0; i < enemies.length; i++) { var div = document.createElement("div"); div.className = "crash"; enemies[i].parentNode.insertBefore(div, enemies[i]); enemies[i].parentNode.removeChild(enemies[i]); } Here the last one is comprehensible but even then, it takes longer for a programmer who just found it to figure out what it is doing; and, caring about other peoples time (and future yours) can be referred as 'kind'.
- _greim_ 13y agoIt isn't that these rebuttals are unsound, it's the sheer volume of them. A tidal wave of irritation and defensiveness always seems to accompany posts that dare question jQuery. Unless the headline was changed by the mods, there's no hyperbole or sensationalism here. You might not need jQuery. Obviously. But many of these reactions don't belong here, they belong in a post titled You don't need jQuery, which would of course deserve to be downvoted to hell. Obviously you don't need to pull in jQuery for every little twenty-line gizmo you publish on github. But don't you dare brag about this or you'll offend the sensibilities of those who've invested all their mental energy into learning jQuery and therefore remained ignorant of how browsers actually work.
- sbilstein 13y agodrop jquery and repeat yourself everywhere
- wnevets 13y agothe dom traversal/chaining in jquery is a big reason why I use it. The native API simply isnt as nice.
- ricket 13y agoBoy, these snippets are really cool! Some of them are a bit longer in vanilla JS, though, so I think I'll wrap them in a utility of helper functions. Oh wait -- that's what jQuery is!
- elclanrs 13y ago"You might not need jQuery" -- But you have to cope with ugly syntax, browser compatibility hacks, and disconnected pieces of code. By the time you re-factor all of this, make it user friendly and lower the cognitive load, you're already re-inventing the wheel by building your own jQuery replacement, with the parts that you need. The beauty of jQuery is working with the DOM as collections. I don't see how it's better to have all these helpers like `nextSibling`, `matches`, or `filter` thrown in the global scope or having to remember is this a real array? jQuery already built solutions for these common problems and exposes a nice API. If all I need is querying the DOM and I don't have to support IE8 then I may consider using vanilla JavaScript, or building my own simple jQuery-esque library. But you'd start with some structure, and expose your own API. I re-invented the DOM wheel many times, and from my experience, although the code is smaller, I end up going back to jQuery because it covers some edge case or provides something else I need, like AJAX, or nice events, etc. But building your own DOM library is a good educational challenge. Querying the DOM is all about collections, and if you don't need IE8 then you can use all the ES5 arrays methods, like map and filter. It all boils down to four functions to work with collections: toArray, unique, flatten and query. And four functions to work with the DOM: compose, join, dot, loop. See here for an example http://jsbin.com/EgIkega/1/edit http://jsbin.com/EgIkega/1/edit. The article is more about techniques to build your own jQuery-like library; I wouldn't use "el.nextElementSibling || nextElementSibling(el)" when I can use "$(el).next()". C'mon! Conclusion, you are probably going to use jQuery anyway.
- hizldizl 13y agoSeeing how many of these hand-picked trivial code examples are still made easier by jQuery just makes me want to use it all the more.
- kirbyk 13y agojQuery's overhead is so minimal. Also, virtually every example of pure js was more verbose. jQueries selectors alone is such a great selling point.
- DigitalSea 13y agoI implore all developers to learn native Javascript methods, because I strongly believe jQuery has created a generation of developers who know the library but not the language. You'd be surprised how many developers I've come across think iterating over an object or array requires Javascript and how many people don't know how to write a simple for or while loop in Javascript. jQuery is a fantastic library, but it is by no means a cure-all for Javascript problems. Now about this site itself. This is a great idea getting people to use and understand native methods, but please also understand that native methods aren't always necessarily the most efficient choice. There are a few of parts of this site I think send the wrong message. Don't get me wrong, I think this is great, but sometimes native methods are no better than jQuery's. The first one being jQuery's each method. It is a known fact that jQuery's each method is extremely slow, it works, but from a optimisation perspective native ways of looping an array are always the fastest and most efficient. The alternative given for a jQuery.each statement is the IE9+ supported Array.prototype.forEach — now you'd think this would be faster right? It's actually still not as performant as it could be. As this jsPerf set of benchmarks shows is that a for loop is the most performant option: http://jsperf.com/foreach-vs-jquery-each/38 http://jsperf.com/foreach-vs-jquery-each/38 — it might not be as pretty as jQuery.each or Array.prototype.forEach, but heck, it's a whole lot faster than the alternatives. The second being the use of querySelectorAll (which is awesome btw). It has similar capabilities to that of jQuery's native wrapper for querying, it looks just as nice, but once again the performance isn't all that great. Looking through multiple jsPerf benchmarks, querySelectorAll is rarely the best option to use in most cases. This is an example of one: http://jsperf.com/queryselectorall-vs-getelementsbytagname/44 http://jsperf.com/queryselectorall-vs-getelementsbytagname/4... — if your selector is extremely complicated, think to yourself, how can I make this easier to write? Do I need to query a chain of five classes and use CSS3 selectors, or can I just add an ID to the element I want and query it using document.getElementById instead. Sometimes jQuery is needed though. It saves considerable amounts of time, especially when the budget of a project is tight and timeline is even tighter and you just need to get something out the door as soon as possible. If you have the time to properly build whatever it is you are building, consider spending that extra 15 seconds writing a for loop to iterate over that array or object. And to those who understand and have taken a look into the internals of how some jQuery methods work like document.ready, you'll appreciate and know just how many different browser quirks the jQuery team have solved for us. There are quite a few methods where jQuery hides the gory details of a sometimes difficult to get right across all browsers feature. Personally my favourite thing about Javascript is the power of documentFragment: https://developer.mozilla.org/en/docs/Web/API/DocumentFragment https://developer.mozilla.org/en/docs/Web/API/DocumentFragme... — this is something all developers who use Javascript need to know about. It helps prevent reflowing and redrawing as well as being extremely efficient and fast for modifying and inserting elements into a page. Over all of this I think we all need to reflect on the state of Javascript. It's a whole lot more powerful and better than it was 10 years ago, but I think because of the likes of jQuery and others, people have become obsessed with pretty code and methods. I know for loops and prototype methods might not be as nice as your one line of jQuery code, but don't take the easy way out, because you'll soon find the longer your Javascript grows in your app/site, the slower it will become.
- julie1 13y agoI may not need jquery for compatibility, I need it because it makes code in a language I find unesthetic and unconsitent more readable. Yes I can do vanilla JS, but my productivity and readability in jquery is better. And this site proves my claim: all their vanillaJS exemple are less expressive and more error prone.
- swah 13y agoIsn't the message about libraries?
- bevacqua 13y agoRelated: Uncoring the Native DOM API http://blog.ponyfoo.com/2013/06/10/uncovering-the-native-dom-api http://blog.ponyfoo.com/2013/06/10/uncovering-the-native-dom... Getting Over jQuery http://blog.ponyfoo.com/2013/07/09/getting-over-jquery http://blog.ponyfoo.com/2013/07/09/getting-over-jquery
- tlrobinson 13y agoThe worst are things packaged as jQuery plugins that don't actually need to be a plugin, or even use much of jQuery at all.
- _zen 13y agoWhy code with Rails instead of raw Ruby? Why code C++ instead of C? Why use Boostrap? Choose one: - Performance - Rapid development
- scotty79 13y agoNext up: You might not need warm water.
- hesselink 13y agoOne thing I haven't seen mentioned in this thread, is that you can create custom builds of jQuery that only include some of the functionality: https://github.com/jquery/jquery#how-to-build-your-own-jquery https://github.com/jquery/jquery#how-to-build-your-own-jquer...
- fatiherikli 13y agoThere is a mistake in Matches section. The `is` method is not equal to `===` operator.
- deleted 13y ago[deleted]
- deleted 13y ago[deleted]
- deleted 13y ago[deleted]
- deevus 13y agoI'm simplifying a bit here: but if we all used the same cdn's client machines would all have popular scripts like jQuery cached and we wouldn't even need to discuss this.
- ahahah 13y agoMy contribution here is that we have a possible acronym troll on our hands. Y[t]MN(NJ) "You're [the] man now, ninja!"? As in: Code ninja? Re-use is fun. See?
- Yaggo 13y agoIn my personal projects (and clients' too unless paid extra), I target for modern browsers + IE10 and haven't used jQuery for long time. Native APIs are good enough once you get used to them. Actually jQuery starts to feel cumbersome (this binding in .each() etc).
- enscr 13y agoI'd love to use a jQuery 'lite' version, just for the convenience and brevity of expressions. Some of it should be baked into javascript.
- finalight 13y agoforget it, i rather just use the jQuery i have better things to do than merely writing my own dependency
- westoque 13y agoActually, you just showed me why I DO need jQuery. Thanks. :)
- dewiz 13y agoApart from size and many functions that translate 1:1, where it really doesn't make sense to use Jquery (time to learn ?) there are two extra factors: 1. the extra http call to load a library, that can be optimized 2. licensing, some company cares about that and avoid the the hassle of having yet another license to understand and manage, there are costs involved I've seen thousands of js snippets using jquery just because the developer doesn't the pure js syntax, or because he is used to start from adding jquery. very good page indeed, thanks for spreading the knowledge.
- hacknat 13y agoMan, the front-end developers really came out of the wood-works for this one.
- chrislomax 13y agoYou might not need [Insert Library Here]. Although this is true, you don't really need any library. The problem comes when you start to need that library. You make a decision to not use it at the start of the project and then the dependency of lower level JS functions grow and it turns out you do need it. What do you do then? Go and get a copy of jQuery and start to rewrite all your functions? Hindsight is the problem here, I'd rather make the decision to use the (relatively) low sized jQuery library and not have to worry about how the project grows. As the old saying goes, "It's better to have it and not need it, than need it and not have it".
- isawczuk 13y agoIt's plain stupid. Your code may work for IE8+, but there is no warranty that M$ will not do something stupid in IE16, and your code will be broken. jQuery is unified bridge between all major browsers, so you don't need to support all of them by yourself. "Support for all" is why we shift from compiled to VM languages, even though at the begin they were slower.
- hipsters_unite 13y agoIt's probably better to have it than not if you're going to be using AJAX, as at least jQuery implements promises (after a fashion).
- puppetmaster3 13y agoMost CSS Frameworks require jQuery. Most designers are familiar w/ jQuery. If you use CDN, some other app likely downloaded jQuery already. People that are not fans of jQuery are people that are are only familiar w/ MVC on client side and are not using APIs (ex: Parse, Kinvey, etc.)
- hugofirth 13y agoI see a lot of people in both camps on this one. It seems to me that if you are making a library, and therefore do not want to make assumptions about the availability of jQuery, one potential solution would be to go the route of AngularJS[1] and have a 'soft' dependency on jQuery. In this instance you would use jQuery if it was present, but fall back on the code found in this submission if it wasn't. Are there potential downsides to this solution that I am missing? [1]: http://docs.angularjs.org/api/angular.element http://docs.angularjs.org/api/angular.element
- BigBalli 13y agono one "needs" jQuery.
- lhorie 13y agoI'm a little sad to see that nowadays there's a strong sentiment of "just use the pre-packaged tool", whereas when jQuery was still in its infancy, there was a lot of lively hacker-minded chatter on the down-and-dirty of getting things to be cross browser. It's as if there are now two "levels" of people - "regular developers" and "framework designers", and only the latter are really supposed to know about the nitty-gritty. The excitement of finding out about standard, cross-browser gems like insertAdjacentHtml is all but gone :( I get it that people are focusing more on the entrepreneurial side of things now, but I miss the banter of aspiring tinkerers.
- rralian 13y agoFWIW, I was on a jQuery-hating kick before I read this article, which explains some of the beauty behind the jQuery api. http://coding.smashingmagazine.com/2012/10/09/designing-javascript-apis-usability/ http://coding.smashingmagazine.com/2012/10/09/designing-java... I agree that you probably only want to use a small subset of jQuery (e.g., none of the UI, none of the transitions), and zeptojs is actually a really good alternative. But it really does provide some convenience.
- fredsters_s 13y ago[Component](https://github.com/component/component https://github.com/component/component). That is all.
- voidr 13y agoSure, why use something stable that everybody knows and loves to use, while you can just add in your custom half-baked solutions. In a post IE8 world adding a minified jQuery library is not a big deal.