240 points · by upheaval7276 · 11y ago · 192 comments
$('#foo').removeClass('bold');
vs. document.getElementById('foo').className =
document.getElementById('foo').className.replace(/^bold$/, '');
The author summarises this, helpfully: "As usual, more characters, but still easy without jQuery."Of course, if you were doing that remove class operation quite often, rather than writing all that code out each time, you might wrap it up in a helper method, and maybe you'd call it, I don't know, "removeClass" or something; perhaps if you were doing a whole bunch of DOM operations you might create little helper methods for each one, again to save you some typing. Pretty quickly you might end up with a little library of helper methods... and, of course, being a wonderful programmer who never makes mistakes, I'm sure that little library would be every bit as optimised, reliable, and correct as a battle-tested library used on hundreds of thousands of web sites.
document.getElementById('foo').classList.remove("bold");
Sure, it's still more verbose. But a lot of what jQuery does is slowly being obsoleted by better native javascript apis.[1] https://developer.mozilla.org/en-US/docs/Web/API/Element.cla... [2] http://caniuse.com/#feat=classlist
If the point of that website was to educate people on the apis that jQuery calls under the hood, it chose a really poor name.
You'd better hope that there actually is an element with an ID of "foo", though, otherwise your example will throw an exception. The last time I pointed this out here, there was some disagreement as to whether jQuery's behaviour is actually desirable. I think it is, but I'm probably biased from writing too much jQuery over the years.
[].map.call(document.querySelectorAll(".foo"), function(node) { node.classlist.remove("bold"); }) [...document.querySelectorAll('.foo')].forEach(node => node.classList.remove('bold')); function ID(id) { return document.getElementById(id); }
saved some typing. I'll always try to use jQuery now though, bigger problems to solve.. few extra bytes to download is not that bad... document.getElementById('foo').className =
document.getElementById('foo').className.replace(/^bold$/, '');
fail if the element in question has more than one class? In that case, you'd need to get the className attribute, split it by spaces, do the replacement in the resulting array, and then join back and assign, I believe.[1]: https://developer.mozilla.org/en-US/docs/Web/API/Element.cla...
document.getElementById('foo').className = document.getElementById('foo').className.replace(/(\s|^)foo(\s|$)/, ' ');
\b is out because it matches - and would kill stuff like foo-bar.So this:
document.getElementById('foo').className =
document.getElementById('foo').className.replace(/^bold$/, '');
Can become to this: foo.classList.remove("x");
And is miles away more performant than slow jQuery.Although, I do occasionally use jQuery, I'm more comfortable and productive when not using it. Also, if I shamelessly take a peek at jQuery's source now-and-then to see how they implement certain features so I can make a helper for it.
You could, but that would require user-agent sniffing (and thus continuous maintenance), and would probably need a pretty unusual caching setup.
document.getElementById('foo').classList.remove('bold');
see https://developer.mozilla.org/en-US/docs/Web/API/Element.cla...The real value of this site is not what it says, but rather a reminder that jQuery is an abstraction and is made of code rather than magick.
Not because of selectors, that's (sometimes) easy to do for lots of (basic) selectors. Not because of DOM manipulation, as long as you're willing to sacrifice simplicity and readability, you can build iterative loops to modify a collection of HTML elements.
No, it's the unexpected things that cause me pain. Want to use event handlers on dynamically generated DOM objects? Write your own event bubbling library. Want to create custom events/handlers? Ditto. Promises, .serialize(), .extend(), etc. might all be simple to write your own version, but when you realize you've reimplemented 50% of jQuery to avoid using jQuery, you feel like an idiot. [Source: I do this every 3 years]
Life is too short to not use jQuery.
Life isn't always a hipster website where people can get lunch delivered on their phone or whatever. Things like jQuery are fine.
https://www.npmjs.com/package/browserify
https://www.npmjs.com/package/react
And then use just what modules you need. All the functionality of jQuery has already been ported to various modules.
https://www.npmjs.com/package/extend
Doing the simple, effective thing is just crazy talk, I tell you.
Browserify is not at all complicated.
spend days choosing between a bunch of almost identical micro-libraries for every little thing you need to do
Just search npm and pick the one that is being used the most.
lock yourself into a proprietary framework that will be considered legacy code as soon as next week’s trendy framework arrives
The problems that npm and browserify solve are at the level of builds and package management. You could use any number of trendy frameworks and tools on top of this.
These are all cool things, but sometimes you want to simply make a web page without setting up node and npm and all that jazz.
Think of it this way... jQuery is like getting a subset of the most common functions you get by using in browserify, but without requiring a build step!
jQuery's imperative DOM manipulation is a horrible way to manage state compared to React.
These tools aren't just "cool things". They were designed to solve really pressing issues related to managing complexity in front-end web applications by eliminating global state in both the DOM or the JS runtime environment. They tend towards a more declarative and functional approach to system design.
A build process that integrates with a versioned package manager is fantastic.
No, absolutely impossible. That would mean I'd have to actually write JavaScript instead of LiveScript and that would be unbearable... ;)
On a more serious note: yes, node is a bit of an overhead. It may be too much for very simple, one-off projects, but it starts making sense as soon as the project becomes even a little bit more complex.
Basically you import everything you need and only what you need. Need extend? No prob: http://microjs.com/#extend - just pick one. And with browserify and npm literally everything you need to do to include a library in your project is a single command, so having to include "that many libraries" is not really a problem.
I'm a huge fan of having many little libraries instead of a few big ones, and JS - both on the backend and frontend - makes this possible to the bigger extent than most other environments.
Real bundling with tools like Browserify is making it more and more feasible to use single-purpose libraries instead of monolithic ones like jQuery.
I agree with all those things. jQuery is the lowest common denominator. It's the best at nothing, bloated with support for Palm Pilot browsers and Safari 1.0, and doesn't have all the cool grunt/gulp/amd/broccoli/cucumber/jsx/fotm neologisms. If I'm building a new, long-term project, I'm going to evaluate all the options, and craft the best possible technology stack for my new app.
But sometimes worse is better. Like a smooth pebble pulled out of a stream, it's taken a long journey and had most of the rough edges rubbed off. It's already in your browser cache from 4 different CDNs. Someone else can pick it up and support it easily. And that's what often makes it the best choice, when you want to avoid bikeshedding over what the hottest new thing is, and just make a webpage.
jQuery may not be the best technology, but it's a sane default.
Thankfully we only support IE9+ where I work, so I grab the latest 2.x version these days.
[0] - http://blog.jquery.com/2013/04/18/jquery-2-0-released/
So ..using jQuery via a CDN, depending on which you use you have a 1 in 119, or 1 in 833 chance of the user having a cached copy. http://www.i-technology.net/2013/11/the-myth-of-cdn.html
more data: http://www.stevesouders.com/blog/2013/03/18/http-archive-jqu...
There are valid reasons to use a CDN (get the scripts closer to the end user, offload the data transfer costs to the CDN provider, etc) but it isn't due to the potential for a cache hit.
https://docs.google.com/document/d/1LPaPA30bLUB_publLIMF0Rlh...
Pretty sure they're not all fixed, and this is just the ignorance du jour.
It's this stupid "you're not a real developer unless you're twiddling bits on your hard drive with a magnet" mentality that I absolutely despise.
That alone is enough reason to use jQuery and not having to bother.
I don't care who caused the problem. Just that it wasn't me, I can't fix it, and I have a deadline to meet and constraints to follow. jQuery is a lifesaver.
If you're worried about dependencies, you could just compile your released library with the Google Closure compile, and strip out everything you don't use. You could even set up a pipeline to produce two releases: one that has bits of jQuery embedded, and a smaller one that requires jQuery.
EDIT: Thanks to dmethvin [1], I just learned that you can also build your own jQuery [2] that only includes the modules you need.
[1] https://news.ycombinator.com/item?id=8760352 [2] https://github.com/jquery/jquery#modules
http://www.i-technology.net/2013/11/the-myth-of-cdn.html
more data: http://www.stevesouders.com/blog/2013/03/18/http-archive-jqu...
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
callback(JSON.parse(xhr.responseText));
}
};
xhr.open('POST', url, true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(JSON.stringify(data));
And that's not taking care of errors, edge cases or Internet Explorer at all.In jQuery:
$.post(url, data)If you're developing a single page application, you only load jquery once, then do the rest with AJAX calls for JSON and assets. It's worth the <100 KB on initial page load, at least for the projects I've worked on.
Forget this "you don't need JQuery"...JQuery, the entire library, is basically an API bug report against the DOM! What browsers need to start doing is get off their butts and start implementing a real selector implementation like Sizzle. Reduce JQuery to set of polyfils after that.
As for IE7 support. Sorry that still accounts for too much of my traffic to ignore.
I'm just saying, you don't need them.
For the eco-system point of view, jQuery have been tested in the widest markets for many many years. well written document, many online cases, many supporters, many bug reporters, high cover unit tests,good code quality and so on.
Using jQuery for project is smart move unless high performance requirement.
jQuery is a framework, like many others. Programming is not about learning frameworks, it's about learning the language, it's runtime behaviours and of course software development in general. Frameworks are there to speed up development time.
better?
I developed a Cordova application recently, and I only needed jQuery for Bootstrap. All custom JS was able to be done using the DOM API. However, I was spoiled since I only had to develop against a recent webkit version (my target was iOS 7)
Just because a lot of people use something that they're not being forced to use doesn't necessarily mean that they've been "tricked" into doing so.
(Sorry ;))
In all seriousness I'd recommend watching Adam Sontag's keynote from jQuery UK 2014 which covers the "not needing" jQuery stuff http://vimeo.com/97723665
http://youmightnotnotneedjquery.com/
or
https://gist.github.com/rwaldron/8720084#file-reasons-md (discussion: https://news.ycombinator.com/item?id=7153630)
Working with the DOM is what we programmers do. I've never seen so many people complain so much about programming than those who use jQuery.
I am not a fan of a lot of the code that I've seen written with jQuery but jQuery itself is not evil anymore than PHP is evil because people do stupid stuff with it. If you use jQuery correctly it is an invaluable tool that makes your like 100x easier.
Event handling alone, I want to puke when I see the default way to do this, way too much typing, way too verbose. If I had to write that multiple times a day then I would probably create a helper function to abstract it away and I'd be on my way to building my own jQuery. No thank you, I'll take the one that's battle-tested and maintained.
I'm getting sick of seeing this argument, if you work in a bubble then sure, be my guest (I'll be laughing at all the extra typing you will be doing) but if you plan on deploying your code to the real world? Just use jQuery and save yourself a headache.
The purpose of an SDK such as jQuery is to help a developer do common tasks without needing to write his own library. If it's used widely in the industry then even better. If it's open source, even more betterer.
I have been considering a project where for various reasons it would be much better to avoid JQuery, and I realized that I had no idea how to do some common things without JQuery. This is a well-organized guide.
It would be even better if he took out the three sentences after every section that just say, over and over again, "So why would you use JQuery, isn't this just as good?"
Who cares, sometimes I agree sometimes I don't, and the boilerplate argument repeated over and over sounds whiny and gets in the way of the actual useful information OP has to impart.
If you have your own external reasons to consider doing without JQuery (as I do), then an _honest_ assessment of where you are likely to have the most trouble would be more useful, than just repeating "Really, you're an idiot if you think you need JQuery" over and over again.
Still, useful documentation, thanks.
https://github.com/Raynos/mercury
See also Raynos's "NPM-style Frontend" presentation:
I think a lot of the issues people have with jQuery is that (as the article mentions) it's become synonymous with Javascript and abstracts so many things that many people using it don't understand the underlying framework and functions. That and why include more resources if you don't really need to.
There are two parallel tracks of JQuery maintained, with _identical functionality_, one which supports IE8 and less, one which doesn't.
JQuery team is supporting both. If they don't behave identically, that's a bug. If you don't need IE8 or less support, you can use the smaller higher-performance JQuery that doesn't support IE8. If you do need IE8 or before you use the other variant.
Your code remains identical either way.
JQuery still supports IE8 and less, and has announced no plans to stop.
A lot of people are confused about this, and it's made more confusing by their mistakes about version labelling.
At present, these two variants are JQuery 1.x (IE8 no problem), and JQuery 2.x (IE9 and above). There are identical parallel versions of each. 1.11.0 and 2.1.1 have identical functionality. Yes, this is super confusing, so going forward in the future, they will call the old-browser-compat variant "JQuery compat", and the no-old-browsers variant "JQuery", and version numbers will be sync'd.
http://blog.jquery.com/2014/10/29/jquery-3-0-the-next-genera...
At present, the JQuery team is still committed to maintaining identical functionality in an old-browser-compat variant, and a newer no-old-browser variant, sync'd, for the indefinite future. And in fact they recommend the Compat version "for most web sites, since it provides the best compatibility for all website visitors."
They could at some point in the future decide to stop doing so -- they have said they won't do so until usage of older browsers has dropped significantly.
Hopefully the change to calling the variants "JQuery Compatibility" and "JQuery" will help -- although since they are still saying they recommend "JQuery Compatibility" for most sites, I think they should have called it "JQuery" (the compatible one) and "JQuery Future" or "Jquery Non-Compatible" or whatever.
Anyway, you also could have simply dropped in the equivalent JQuery 1.x version for old-browser-compat with no changes to your code.
Yes it's useful to know what jQuery is doing underneath but the whole point of it is that you don't have to worry about that and can concentrate on on the rest of your build.
Sure, you might not need it and there are other alternatives, both as plain JS and with other libraries, but it does it's job well and will always be easier for others to pick up when coming onto a project.
http://blog.jquery.com/2014/12/18/jquery-1-11-2-and-2-1-3-re...
> "A bug like this one emphasizes the benefit of using a library like jQuery rather than going directly to the DOM APIs."
Oh the eyes of Microsoft shine gracefully upon us, we are so blessed. First, get a spell checker. Second, abandon jQuery at you peril. Browser makers should be required to embed jQuery. jQuery makes JavaScript almost bearable to deal with. That says a lot.
"This is your reminder that the DOM is actually a giant,
mutable, global variable in the middle of your program.
Act accordingly." –Marco Rogers (@polotek)
https://twitter.com/polotek/status/543590973846999040If you are using just the basic JQuery features you could consider Zepto instead, so a smaller download but still giving you the abstraction you desire.
http://stackoverflow.com/questions/11503534/jquery-vs-docume...
So no, I disagree. Stupid article.
$ = document.querySelector.bind(document); $$ = document.querySelectorAll.bind(document);
I think the rest of us will rather keep on using it, or similar library.
Fear or Love on the web developer scale of needs.