310 points · by andyonthewings · 8y ago · 250 comments
jQuery has many convenience features such as chaining, for example: item.addClass('selected').siblings().removeClass('selected'); and you don't have to check for nulls after each selection.
Many functions such as closest() and remove() have no equivalents in IE11, and other things such as replaceWith() and before() are not available even in Edge.
For simple sites it is easy enough to remove jQuery, but for more complex javascript applications, especially apps that have a lot of interactivity, removing jQuery will result in more code, or you will end up writing a lot of utility functions thereby creating your own little clone of jQuery.
Ultimately, I haven't actually used jQuery for anything serious in half a decade, and somehow I manage.
I don't understand that sentiment ... Of course you can "manage" without JQuery. JQuery itself doesn't use JQuery (D'oh) and somehow it can do all these things, so it is possible. The point of JQuery is that I don't have to think about the various (slightly) incompatible implementations of <whatever> in each browser version, but can just use one lib call and be done with it.
JQuery to me is like using a car instead of running to another city. Yes, I could run, but why would I do that ..?
Browser incompatibilities are basically a non-issue these days for 95% of projects. Animations etc are far better done with CSS than jQuery (particularly when it comes to hardware acceleration). The Fetch API works in every browser. So on and so forth.
I think the OP wasn't suggesting that "managing" without jQuery is difficult. Certainly, I can say that I haven't touched jQuery in years and haven't looked back once. There's nothing I miss.
Sure when jQuery was released in 2006, but browsers have had 12 years to improve their compatibility, and they have. Javascript has also had 12 years to improve and simplify its api, and it has.
Your analogy was perfect for jQuery 2006 but in 2018 its more like buying a car to drive around the city or you can just take an Uber, you don't have to walk anymore.
> If you're developing a library on the other hand, please take a moment to consider if you actually need jQuery as a dependency. Maybe you can include a few lines of utility code, and forgo the requirement. If you're only targeting more modern browsers, you might not need anything more than what the browser ships with.
Back then, you were 100% correct that if you were writing a library that you intend to use in other places, having jQuery as a hard requirement was a bad idea. However, one developer managed to convince their PM's to completely strip out jQuery for an upcoming project, despite the fact that this website was for a major charity that had huge accessibility requirements AND required legacy browser support. The devs on that project learned a ton about vanilla JS, but that project was an absolute disaster.
We did get a solid library out of it, though, and at least that didn't have jQuery as a dependency!
Did that convincing developer have more influence than the rest of the team? Why the PM was involved in implementation minutiae?
From what I've seen people tend to complain about office politics usually when they don't grok them. The not grokking part is often a choice stemming from a conviction that code monkeys > managers because "engineering". Following your example, who then has more influence over technical decisions? (at least in your somewhat disfunctional org?)
Point is:
$('#somediv').removeClass('class-to-be-removed')
is so much better than
document.querySelector("#somediv").className = document.querySelector("#somediv").className.replace(/\class-to-be-removed\b/,'');
document.getElementById('somediv').classList.remove('class-to-be-removed')
Where the native APIs fall down is that1. they tend not to be chainable/expression-oriented, you can't just `classList.add('foo').remove('bar').toggle('qux')` because the first two methods return `undefined` and the last one a boolean
2. they don't support set-oriented operations at all, it's a chore of manual iterations
License is MIT.
Unfortunately it seems to be unmaintained.
What's with the trend "jQ is old, old is bad! We need something that does the same thing, and most importantly is not named jQuery"?
But in this case (as in many others), code is written just a couple of times per month, and executed millions of times per day in millions of computers all around the world.
Therefore this kind of "low level JavaScript"* optimizations will have a net benefit much, much bigger than the convenience of reading shorter code for a relatively small group of people.
* Quite the contradiction, I know.
Writing code which just works on multiple browsers results in faster development and easier to maintain code and frees dev cycles to focus on performance.
Perhaps this is the case--jQuery saved them so much time that they've reached a point where they are free to optimize their frontend by removing jQuery.
That argument sounds very postmodern. The main issue with perception is that it easily tricked and even more, it can be strongly influenced by bias.
The cumulative effect can surely be measured and reasoned about.
It is very different to program for your new startup idea where adding features faster than your competition is more important than anything else in order to grow your user base, compared to improving an established product already being used by millions of people.
Different needs, different approaches.
async function printExampleCom() {
let response = await fetch("https://www.example.com/")
// NB: Response has other methods like json.
console.log(await response.text())
}
printExampleCom()
You need a polyfill for `Request` for Safari and Internet Explorer (but not Edge), but that's about it.Or stated differently, "jQuery is just a JS polyfill for browsers that don't support native jQuery yet."
I agree with JQuery for the most simple sites, but React+transpiler will give you much better compatibility
Our company built an in-house front-end framework heavily inspired by React and Vue. The components built using the framework work with or without jQuery. No manual DOM manipulations, one-way data binding, sane state management, templating, etc. Many of us prefer to use jQuery because of how compact and expressive the syntax is.
It really surprises me how many people think that jQuery === old school manual DOM manipulations. It definitely doesn't have to be that way.
React also let's you mark areas/divs within its domain as "don't touch this". So in those areas you can use things like that old map widget you love so much, without resorting to iframes
Angular is a huge fail in this regard. Zero support for mixing with "non angular" pages.
Having worked in complex interactive React/Angular apps as well as ones using JQuery, nobody would ever offer me enough to use JQuery again for this use case. They would have to double my pay for all the pain
Many of these can be polyfilled, Going the polyfill route IMHO is a bit better. I use this now : https://polyfill.io .
That polyfill relies on nothing since you can run your own custom 'polyfill' server, or just download the bundle and serve it from your website. It's completely open source.
https://github.com/Financial-Times/polyfill-service
You're complaining that a public CDN runs some analytics. But they all do that, and this project doesn't mandate that you use their CDN.
Huh? http://youmightnotneedjquery.com/#replace_from_html and http://youmightnotneedjquery.com/#before show solutions that work in IE8+ and Edge.
Here it is in the form of a basic polyfill that only supports Elements:
Element.prototype.replaceWith = function(replacement) {
if (typeof replacement === "string") {
replacement = this.ownerDocument.createTextNode(replacement);
}
this.parentNode.replaceChild(this, replacement);
}Further, there are many better animation libraries.
And finally if you use any view framework you have very little need to be traversing the DOM.
fetch('/my/url').then((r) => r.json()).then((data) => {
})
And as an added bonus, fetch uses promises, so in an async function that's just: let data = await fetch('/my/url').then((r) => r.json()) let data = await (await fetch('/my/url')).json();
That's a one-liner, but you can split the request and json data as well (and you usually want to anyway because of error handling).But if you had a small site that just needed to perform a few DOM manipulations, this would be highly relevant. If I just need to pop a div open and closed when a button is clicked, I sure won't bring in jquery just for that.
The performance question becomes a bit more tricky too then, because instead of comparing direct DOM manipulation you're comparing 'rendering' as a more abstract concept.
$(document).on("click", "#foo", function(){...});
either
document.getElementById('foo').addEventListener('click', function() { ... });
? $(document).on("click", "#foo", function(){...});
is: document.addEventListener('click', function (ev) {
if (ev.target.matches('#foo')) {
}
});
The advantage is that #foo can come and go (after page load be injected and removed and injected again, but the event listener must be registered just once.Since the example is an ID (#foo) the advantage is less obvious. Something like a class (.foo) makes it clearer that there could be many, and it could get expensive to attach an event handler to each one --- though I'm guessing it takes hundreds before it becomes a big deal. But again, .foo's can come and go without having to worry about reattaching the event handler.
P. S. My library, https://github.com/combatentropy/listenup.js (31 lines)
The jquery example delegates #foo, so it can be injected in the page after load and the click event will still work.
But there are ways to mimic the behavior as another person has pointed out.
How so?
You have an instance. You're allowed to call methods or access properties of that instance. You're not supposed to call methods or access properties of properties.
So chaining is just:
$foo.something().somethingelse().blah();
At each point you're getting a new instance and accessing that. You're never reaching inside of a property of that instance.For me it has always been about performance. jQuery is slow. Even way back in the day before JavaScript got fast you could access the DOM quickly if you knew what you were doing. Likewise DOM access could easily make your code 5 times slower if you didn't know what you were doing.
Since 2012 JavaScript has been fast in every major browser and querySelectors are a standard feature. Since about that time accessing the DOM has always been 10s-100s of times faster than using the standard querySelectors. In Firefox it is 10s of thousands of times faster. The standard querySelectors are faster than using modern jQuery.
To me this is the difference between a junior developer and a competent developer. Some people NEED the extra help. I understand that. If product quality and achieving a superior user experience are important though you will simply figure out a better way of writing code, especially since writing code is probably your job.
I've worked with developers who completely ignored good libraries and instead created their own terrible implementations. They got nothing done and what they did was a buggy mess that often needed months of patching.
Finding a good middle ground is the best way to go and when the loading time increases by only a few milliseconds, but the development is a lot faster and cheaper, that's a good compromise in most cases.
In this case every call to the DOM goes from a slow baby crawl to rocket speed. In no other aspect of life do people make such empty excuses, using cliches no less, to intentionally remain in the stone age.
I think it's impressive that even when I'm not using jQuery (haven't in many years), I find myself writing code using features/capabilities where jQuery was an obvious inspiration.
(a) cross-browser compatibility, which mostly works now (except for cutting edge stuff, which is pretty optional) (b) $.ajax (uses that could be replaced by window.fetch) (c) Sizzle (Replaced by document.querySelector[All])
I had used Prototype.js, and just a couple years ago finally gutted it from our code base. And shortly after started removing jQuery. It's a long slow process.
After starting with Vue.js, I completely understand why jQuery is no longer needed. Vanilla JS/CSS3 does 98% of what jQuery did for us, and our own micro-library fills in the blanks. And Vue is replacing all the jQuery scaffolded apps.
If it weren't for reactive interface libraries though, jQuery would still be a staple.
One example, I use a jQuery library for sorting tables. When I saw how sorting a table is so basically easy in Vue.js, that no plugins or 3rd party code needed, I saw the downfall of jQuery in general.
Jquery is JUST jquery. There is no pulling in 300 other packages to support it. It's also very stable, reliable, efficient enjoyable.
this is how you might sort a table using a Jquery library:
$("#myTable").tablesorter()
And here's how to do it in Vue (first search result for vue table sort):
https://www.raymondcamden.com/2018/02/08/building-table-sort...
You'll note that it is a lot more code to sort with Vue than with a jquery library.
Don't get me wrong; I like Vue; But Jquery offers one line of code that enhances the existing HTML you have, where doing it with Vue.js requires delegating the entire table render to Vue, which may not be easy or even doable depending on the project.
I think things like Vue.js or stimulus.js let Jquery do more with what it's good at and less of what it's not. I'm very happy to have Jquery in my toolbox and I doubt I'll ever stop using it at this point. You're welcome to hate on it, call it dated or what have you - i still love it and it's still the best tool for quite a lot of jobs.
It’s not a fair comparison.
"It's like eye glasses, you'll know when you need them" - Some smart guy
I needed something jQuery could not provide, easing my work load.
Let's look at this from 2 different perspectives:
1. You're building an app, and work with multiple tables to render and work with. And you have integrated form elements with the table cells that affect other cells. You need to add/remove items using AJAX data calls to the server and sync the display with the server data. And you fully expect to be making more changes in the future.
2. You have a table on a website(s) as content you want sorted.
I've used jQuery to do both, but with Vue.js I cut my code base down by 1/10th at least, and it works smoother and easier and way easier to extend and add new features.
I have used jQuery exclusively for all my front end work, but I have an app that just kept needing more and more features. And every time I had to add a feature I went through so many hoops and patching stuff and dealing with edge case uses, and _hoping_ the jQuery plugins I was using had my back when I upgraded jQuery, or when I needed just a slight tweak on how a table was to be manipulated.
With Vue.js, adding sorting to a table was literally 5-10 lines of code, that I have total control over. This is possible because I don't have to deal with the html directly.
I was a die-hard jQuery man just last month, if you have the time, read my other comments, I defended it to death. And yes, it still likely has it's uses, but in my experience (full stack dev for almost 20 years) I can do everything jQuery can, and often times better, on my own now. jQuery can "simplify" some code, but that doesn't make the code easier to work with or extend, it just makes it "shorter", which isn't much value anymore to me.
Regarding this example: https://www.raymondcamden.com/2018/02/08/building-table-sort...
That's not extra work because I replaced my server side render of the table (which had a library for rendering tables) to doing it entirely on the front end. I just get to pass it data. (yay!)
Also the jQuery plugin I use is hugely bloated, and I only need a fraction of the features.
I have thousands of lines of code using jQuery still active in my code base. I just started with Vue.js last week, and I only tried it because I was so daunted by my tasks ahead to build a version 3 of an app. Within a couple of hours of development everything got easier.
If you don't experience this when using Vue.js (or other reactive library), then jQuery is obviously perfect for you.
--
Edit: This is the jQuery table sorting plugin I used, because I needed heavy duty features.
https://github.com/Mottie/tablesorter
In total, 240k MINIMIZED code plus css, images, etc... The file size alone is incredible. When I am done making a proper component with Vue.js to do the work I use this for, I bet it will be 10k or less easily, and that will include the html scaffolding and rendering to boot.
For a blog post jQuery is just fine. For a fully supported long term app that produces income? Vue.js all the way, even for something as simple as sorting a table.
--
Edit: Consider if you want to change from a table to divs with grid? Or list? You can't with jQuery because you only have a table sorting plugin. All it's classes and rendering are for tables.
https://jsfiddle.net/rg50h7hx/788/
Look how little code it takes to sort the data in that example. This was just crazy to me when I first ran into this.
Here's the actual example I ran into that opened my eyes to the simplicity of using data to render the html through Vue.js
http://www.developerdrive.com/2017/07/creating-a-data-table-...
57 lines of js code for sorting, pagination AND data for the table!
Besides jQuery there were several competing libraries abstracting the browser inconsistencies: YUI (Y=Yahoo), prototypejs, mootools, dojo. So I'd say multi-handedly.
Strong leadership without the bickering and bikeshedding that ruined its competitors.
The first time around was rails with HAML/sass, with a light sprinkling of jquery used like CSS, mainly to make things like sortable tables, search w/ typeahead find, and a few other fancy things work. The second time around I used rails as a REST api and wrote an angular 1.x SPA for the frontend.
Honestly, the first time around was far, far nicer from a developer ergonomics perspective. Just writing your HTML in nice reusable, composable templates, even though there's a lot of scary abstraction violations being able to access @variables from your ruby controllers, was a very straightforward experience. And the jquery was used mostly like CSS with something to the effect of `$("input.search").search({...});` to just apply a jquery plugin to all css-selected elements indiscriminately. And you know what? It was pretty darned easy! Move onto the next problem.
My angular experience was far more complicated, and building the SPA was a level of effort on par with designing an entire application from scratch, with almost as much time spent developing it as I spent on the backend code.
You can talk a lot about how jquery isn't necessary because you can do equivalent stuff without it, and I'd totally agree, but it was just the perfect tool for what I needed it for at the time. Lots of awesome plugins to enhance (with graceful fallbacks) the views that rails spit out, without me having to write anything. Angular had lots of cool plugins too but the level of effort was just too high.
But, the point isn't that those things exist or that there are a lot of them. The point is that jQuery's biggest value add, at the time, was it had a very consistent and fairly fast development across several browsers. In the bad old days, IE, firefox, and Safari all had vastly different and divergent sets of features. Heck, half of the stuff jQuery did was stuff you should be able to do with CSS but couldn't because of how differently CSS behaved across browser. This was one of the biggest value adds of jQuery. (I went through the bad old days.. they were hell)
And I do not always recommend it, indeed for smaller projects you might be better off with plain Javascript: https://umbrellajs.com/documentation#native-methods
But native Javascript, as explained there, is more error-prone while jQuery (and Umbrella) are more permissive. Both have their pros and cons, but if you try to make native Javascript as permissive as jQuery you'll end up with a big mess. Unless you create some internal methods, which then you bundle, test, release, and... end up with another jQuery clone!
You'll likely start wrapping these methods, and before you know it, you have jQuery-micro.
My application doesn't use much JS so this seems reasonable to me instead of including a framework for a few functions.
- knows what it is, i.e. a web javascript module, it doesn't try to inappropriately wrap itself in CommonJS/AMDJS wrappers
- doesn't need node/npm to run
- doesn't need node/npm to build
There's also an official slim build without ajax and effect modules.
let $ = document.querySelectorAll;
If you mean chaining commands you can use the latest version of jQuery. It uses querySelectorAll under the hood.They bragged, about the single worst web UI I have to use on a daily basis. Github.com combines the worst elements of static and dynamic web-pages:
- If something gets updated on the backend, it will update on the frontend
- Except all the times it doesn't
- If you change something on the frontend, it will update on the page - Unless you interact with the page in any way after that, like changing tabs???
What you end up with is a frontend that uses a lot of AJAX, but still requires constant hard refreshes to see accurate information. It's an absolute disaster.Somehow all the time I'm doing JS, people were talking about how jQuery was "an old library" and "the old way to do things" even in 2011.
2 years ago I was on a JavaScript meetup and some guy, who did interfaces for stock trading, said: "We had to write our own framework, because jQuery just didn't cut it anymore!"
I just thought, no shit, it's 2016 and NOW you talk about replacing jQuery? Since its inception I used 4 different frameworks and even when I started in 2011 it was already "old news". Where have you been living if you had the impression there is only jQuery and "your own framework"
I don't see why it being old is an inherent problem.
I want to clarify a bit about "JA Hate" though: Most of it stemmed not from JQ's limitations or age, but rather as a matter of architecture. While it's cool these days to smugly enjoy the options of vanilla JS, JQ hate was around before those standards were reliably implemented.
JQ really stepped in when dynamic web pages (i.e. pages that modify their own HTML without page refreshes) were becoming a thing. AJAX calls were new (to most) and exciting. form validations that didn't require 2-3 seconds to load, etc. All made far, far easier by the APIs JQ had.
BUT there were complications: JQ plugins meant that having multiple copies of JQ on the page tended to not work well - and that happened if you were mingling content sources. JQ didn't require it, but many coders would use the DOM to store data (JQ made it so EASY), which worked well short term but caused troubles. Example: If you have a list of items, with every other item shaded, and every item had some metadata in the HTML, and then you wanted to remove some items, what did you do? More importantly, when you wanted to restore them, where did it come from? If you were tracking everything in a JS variables and building the DOM, no problem, but if you were using the DOM to hold your data, you had issues. Even if you WEREN'T using the DOM to track your state, repainting all the DOM got expensive - a table of 10 items worked great, but a table of 1000 could bog down terribly.
Ultimately someone would inherit (or create) a convoluted mess of JQ and blame JQ rather than the creator.
Much of the JQ hate came not from JQ flaws, but the flaws of coding done in the face of JQ success (as has happened with so many languages/libraries/frameworks before and since). We've learned from those flaws AND successes though - querySelector() basically uses the sizzle syntax; modern virtual dom libraries deal with the DOM pains; be it React's Unidirectional flow or Angular's two-way binding, the goal is not to use the DOM to hold state; and every AJAX library out there tried for a better interface (arguably fetch() beat them all). We're still hashing out how to handle reusable pieces of non-static HTML, but there are many options.
So congrats to anyone that doesn't need JQ, and no hate to those that use it if they strive to use it well. I can only hope to write something hated for the results of success that nonetheless leaves the world better off.
The one feature I miss that jquery has is dialog boxes that can be customized with HTML.
Does anybody know of any cross-browser javascript dialog functions?
If you use some of the weirder stuff in jQuery or use plugins you might end up doing some targeted refactoring or just porting that code but I found it a relatively painless transition to make.
Tip: write unit/integration tests for the code you're about to convert as it makes the process much easier and faster.
Custom elements are probably a great fit for .erb templates.
With querySelectorAll, you have to iterate over all the matching elements. Do you use some shortcut?
"Fewer kb sent to visitors, more explicit syntax when performing DOM manipulations, ability to use Flowjs for static type checking"
Browsers are more standardized today because of it, but what will come in the future when there isn't a library as widespread to help that effort, probably more fragmentation and eventually more jQuery like libraries whether that is polyfills, vdom kits, wasm, based and more.
jQuery also created a rare simplification in the front end fast moving javascript eco-system that standardized a well tested across all browsers library that made front end development easier rather than more complex. There aren't lots of libraries like it today that look to make things more standard and simple rather than adding monstrous monolithic abstractions that are brittle to change, yet change every few months causing brittle/flaky development.
As a webdev that developed javascript before jQuery and all the others (mootools, prototype, scriptalicious even dhtml etc) it was a very welcome library and may not be understood how impactful it was to development speeds and a market standard that really helped ship products.
I feel like jQuery gets lots of underserved hate just like javascript itself does, meanwhile they are very useful, helpful and needed tools. Tools that simplify over adding more complexity are needed, some engineers just like to add complexity which makes them seem smarter, when the job of an engineer is taking complexity and simplifying it. jQuery simplified over adding complexity. jQuery always made team developments more robust especially with juniors on the squad, you could at least know jQuery was tested and focus on the implementation and app over internals/support/browsers. jQuery is a perfect simplified abstraction of common javascript needs that standardized development from signatures to usage and eventually browsers. Just like javascript itself which has simplified web apps and development, jQuery's simplicity and usefulness went well beyond the call of duty. Believe it or not, jQuery is still a good library and that is mainly because its mission is to simplify complexity. I feel like some of the hate against jQuery is because it simplified too much and people that like to add complexity felt it made them seem less than, comments like "it didn't even need jQuery but the samples were in that anyways" were because jQuery was a simplification and market standard most of the time, and that is ok, platforms are built from good cornerstones and libs you can trust just like native/browser standards themselves.
I do lots of projects, some with jQuery and some without, the ones with jQuery still seem to get less in the weeds of browser standards/capabilities than the ones without. Native js is much better by far but even jQuery uses most of that now. The other areas of jQuery like animation are not as useful anymore (CSS animations). However it is still nice to have jQuery at times because without jQuery, even with most of the useful tools available natively in javascript, it is a common signature/library that when not present still leads to other people making their own helpers and re-creating jQuery at least the useful parts i.e. selectors, event handling, ajax, dom etc.
Thanks jQuery and John Resig, we'll need more libraries like you in the future to bring front end dev back to sanity and see though standards fragmentation again one day, for now that is numerous polyfills and vdom kits. Let the best of the warring new jQuery's win. "The reports of my death are greatly exaggerated" - jQuery