In every single example, the jQuery version is basically one or two lines of code, versus 10-15 lines for the alternative. (and the jQ version seems significantly easier on the eyes as well.)
Also, jQuery supports promises and has for quite a while.
This page hasn't aged well. I've come full circle and am now using jQuery again.
For reference:
// JSON
const data = await (await fetch('/my-url')).json();
// Post
await fetch('/my-url', { method: 'POST', body: data });
// Request
try {
const resp = await fetch('/my-url');
// ...
} catch (e) {
// ...
}
// Fade In
el.animate({ opacity: 1 }, 400);
// Fade Out
el.animate({ opacity: 0 }, 400);
// Hide
el.hidden = true;
// Show
el.hidden = false;
// After
target.after(el);
// Append
target.append(el);
// Before
target.before(el);
// Each
for (const el of document.querySelectorAll(selector)) {
// ...
}
// Empty
el.replaceChildren(); // or el.textContent = '', depending on which you find clearer
// Filter
[...document.querySelectorAll(selector)].filter(filterFn);
// Get Height
el.clientHeight;
// Get Width
el.clientWidth;
// Matches
el.matches('.my-class');
// Remove
el.remove();
// Delegate
document.addEventListener(eventName, e => {
const match = e.target.closest(elementSelector);
if (match) {
handler.call(match, e);
}
});
// Trigger Custom
el.dispatchEvent(new CustomEvent('my-event', { detail: { some: 'data' } }));
// Trigger Native
el.dispatchEvent(new Event('change'));
// Extend
Object.assign({}, objA, objB);
// Parse HTML
(new DOMParser()).parseFromString(htmlString);
// Type
obj[Symbol.toStringTag]; const resp = await fetch('/my-url')
if (!resp.ok) throw new Error(await resp.text())
const data = await resp.json()
From MDN (https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API):> The Promise returned from fetch() won’t reject on HTTP error status even if the response is an HTTP 404 or 500. Instead, it will resolve normally (with ok status set to false), and it will only reject on network failure or if anything prevented the request from completing.
I also don't care much for the fetch() API; I dislike promises and what does it send when you try to POST a JS object ({foo: 'val'})? [object Object]. Yeah, useful...
And even in 2021-jQuery, it still works around some browser bugs and inconsistencies, even in modern browsers. Much less than it used to, but not zero either.
It's hard to overstate the impact of jQuery. It more than doubled my productivity due to removal of much of the duplicated work AND the general streamlining of DOM manipulation. As someone who was also neck deep in XML and XSD, the element selection syntax also felt reasonably familiar and comfortable.
> Loading the entirety of jQuery just to access some of the remaining features just means you're loading JavaScript that you aren't going to use
Isn't this the penalty for every single library we use. At most we can use about 20% and the rest is just out taking space.
Browsers got to this point because jquery pushed for it.
JS people be like: "86K jQuery dependency is wasteful!"
Also JS people: "why do you care that an SPA loads 2M of JavaScript? Are you stuck on a 56k modem or something?"
Yes, absolutely. That's a total no-brainer.
> Hidden complexity you don't control is the most expensive kind I think.
There's oodles of hidden complexity you don't control in any modern CPU, but most developers (rightly!) don't care. Complexity you have to fix bugs in is the expensive type, but IME you're far more likely to hit bugs in your custom implementation of whatever it was than in jQuery.
That's called encapsulation. :)
Seriously, encapsulating complexity is the foundation of most programming paradigms.
I don't actually use jQuery any more but obviously if you are using it, you are saving the 10-15 lines every time you use one of these methods, not 10-15 lines in your whole application. I have a hard time believing that the savings of code lines will not be close to the weight of the dependency in any medium sized company codebase.
Jquery is a thin wrapper over javascript, whereas React has a comparable size but is a significantly higher level abstraction.
There's projects like https://umbrellajs.com/ which are very similar to jquery's APIs for DOM manipulation and it's only 2.5kb gzipped.
IMO it's a nice balance between having a convenient API without bringing in the world.
If I could write 2-5x less code and it's easy to remember I would make that trade off every time.
That said, optimization techniques have gotten good enough that you might be able to just let a build tool do that for you. If you really still want to use jQuery.
"If you're developing a library on the other hand, please take a moment to consider if you actually need jQuery as a dependency"
Counterpoint, if you're developing a library, then (based on this page itself), each line that would depend on jQuery would otherwise balloon to 15 times as large, so maybe the highly optimized jQ dependency would be worthwhile if the extra functionality would actually be useful (or perhaps "slim" jQuery). The savings would increase for each additional library that had a shared dependency on jQuery.
But, anyway, developer time is valuable, and the 80kb or so for jQuery will probably be blown away as soon as you stick a single image on the page.
"Every single example?" Are we reading the same page? I was fairly surprised to find that 75% of the alternatives are literally one-liners. There are a handful that swell up to 10-15 lines of code, but I would say it's a very small portion, far from "every single example."
This page is just outdated. IE10 is a now deprecated browser whose last release was 4 years ago according to Wikipedia.
(BTW, the baggage of supporting old versions of IE was removed when jQuery 2 was launched in 2013. There's now also a "slim" jQuery that removes a few features for a smaller file size.)
Even the old jQuery seems easier to read than the modern ES6 equivalent (IMO).
jQuery:
$(".classname").addClass("darktheme")
ES6: document.querySelector(".classname").classList.add("darktheme")"jQuery and its cousins are great, and by all means use them if it makes it easier to develop your application.
If you're developing a library on the other hand, please take a moment to consider if you actually need jQuery as a dependency."
If you're shipping a big application and need to use a large number of these utilities, by all means use jQuery. But if you're shipping a small library and only need one or two of these functions, you might want to forgo the dependency. Using jQuery in your library forces it as a dependency onto everyone who uses your library, potentially making them deal with version conflicts if your version of jQuery doesn't align with their version of jQuery (or the version that another dependency wants).
But isn't the point here that you can wrap the 10-15 lines into your own function which you can then call with just a single line of code?
So you "might not need JQuery" because you can program it yourself following the examples given, and can choose which parts of it you need and want to package with your app.
You could do that for any software, not sure what you gain from doing it though.
On the web, user experience should really be a higher priority than developer experience.
> On the web, user experience should really be a higher priority than developer experience.
Those aren't disconnected. The more time I spend on technical implementation details, the less time I have to think about UX and/or implement things that improve UX.
But, either way, it really depends. If you are writing a large application and jQuery saves thousands of lines of boilerplate, then it's totally worth it. For a tiny library (which is what this page is targeted at), then it's probably overkill and you should learn how to do it manually with pure JS. Both can be true at the same time.
The only reason to reach for jQuery, IMO, is familiarity. If you don't want a framework, then just write vanilla js.
It's heavily inspired by "You might not need jquery" as the intro shows! Lots of the methods are just like in these examples, only with looping/multiple nodes. Example:
$(el).addClass(className); vs el.classList.add(className);
Do not work the same. jQuery (and Umbrella JS) deal with multiple elements and with multiple class names in multiple formats (as a string, as arguments, etc). That's why I find myself still using Umbrella JS from time to time in smaller non-React projects! Just makes everything a lot easier, for 3kb.
Hacks with :checked are well known, but you can do a ton of stuff with :focus-within, :invalid, :target, :hover, <details>/<summary>/[open], grids/flexbox/visibility, and the adjacent-sibling selector. <dialog> is almost there, although it still needs a JS activation hook.
It feels really good to have a complete application UI that works with JS disabled, and I can still progressively enhance it with JS for necessary perversions of HTML like ARIA etc.
WebComponents can do just a fraction of what React/Vue do, and it's just the least interesting parts. The encapsulation is great, of course, but it was already possible to have "reusable components" back in the jQuery days and before.
All the WebComponents usage I've seen professionally lately were wrapping React/Vue or using some other lightweight framework that does something similar.
Not saying WCs are bad tech: just saying I think there are some great ideas in Vue/React that still don't have a native API. Would LOVE to see a new version of WebComponents adopting some of those ideas (only the good ones though haha)!
As well as the form issue, what made webcomponents untenable for me was that you can't use slots without opting the whole component into CSS encapsulation.
Great if you want to distribute components without fear of the consumer's CSS messing with your styles, absolutely useless if you want to extract common patterns in your own app because now you have to duplicate the relevant CSS in every component.
That said, I was once a single page app skeptic but I now think React and Vue are great alternatives to HTML/templates that compile to HTML if you have a reasonably complex front end. Pre-React and Vue, in the Angular.js/Ember.js/Backbone era, SPAs were not in a stage of maturity that made it simple or optimal to use them as a primary front end. Today I'd say for a complex FE go ahead with React or Vue, if you have a very simple FE, definitely consider HTML/template-to-HTML as a serious option.
(and no, I don't mean WebAssembly - bring back static websites!)
Sorry to pick on your post over the million and one other ones that pop every time jQuery gets mentioned in HN (same for the "look at my my blog website that just uses HTML/CSS" posts), but why is it silly? There's no halcyon period where it was simpler and easier, and the tools are in general much better than they were.
Because of bloated frameworks and slow convenience libraries the front end is a very low barrier of participation. The problem there is then that peoples’ entire careers and life worth are stacked around these fragile glass houses and the only thing they want is to avoid being exposed as a fraud.
Is writing a killer product without all the bullshit that impossible? No, clearly not, but that completely misses the point.
- Got rid of redux because it's shit
- Got rid of Material UI because it's bulky and its API changes are painful, replaced it with tailwind
- Got rid of React Router because it's bulky and its API changes are also painful, replaced it with a simple hook
As someone who worked on large jQuery apps before React, I think most people would jump back into React or Vue in the first chance after seeing a non-trivial jQuery app. Not to mention there was a lot of "bloat" in those apps, too: Backbone, Bootstrap, Moment.js...
jQuery was amazing for small things, for landing pages, for some Bootstrap components here and there, and for sprinkling the page with progressive-enhanced features. And it still is probably the best choice.
But it was not a great fit for moderate-to-large apps. And it was a terrible fit for moderate-to-large apps that only consumed data from an API.
Not saying React and Redux are good, but I think at least the parts of React, Angular and Vue that replaced jQuery were definitely a step in the right direction.
I'm also not saying that "big apps" are the way to go. If I could I would go back to server-side rendered HTML and modern CSS, but it has become hard to find developers that are into it.
I strongly recommend reading through the newly rewritten official tutorials in the Redux docs, which have been specifically designed to show our recommended practices:
- "Redux Essentials" tutorial [0]: teaches "how to use Redux, the right way", by building a real-world app using Redux Toolkit - "Redux Fundamentals" tutorial [1]: teaches "how Redux works, from the bottom up", by showing how to write Redux code by hand and why standard usage patterns exist, and how Redux Toolkit simplifies those patterns
The older patterns shown in almost all other tutorials on the internet are still valid, but not how we recommend writing Redux code today.
You should also check out the Redux "Style Guide" docs page [2], which explains our recommended patterns and best practices, and why they exist. Following those will result in better and more maintainable Redux apps.
[0] https://redux.js.org/tutorials/essentials/part-1-overview-co...
[1] https://redux.js.org/tutorials/fundamentals/part-1-overview
Look at svelte if you haven’t.
It doesn't have a compilation phase but it allows us to use Preact, and it's only 5k.
They're listing APIs that you used to need jQuery for that are now natively supported by the browser. This is for people still doing the jQuery style of development.
Oh wait...
If we're really clever we can probably get it up to several megabytes, require three languages and have it run from an embedded C compiler written in Webassembly.
Of course, it will only work in Chrome but really who wants to waste time testing in browsers nobody even uses amirite?
We're not in kansas anymore.
https://en.m.wikipedia.org/wiki/Program_optimization#When_to...
If your code can execute 10x faster without jQuery then the optimization is not premature. If a developer takes twice as long to write any code the problem isn’t optimizations at all.
One could argue that it is premature if the code doesn't _need_ to run 10x faster.
If you optimize process of delivering feature to the end user then using JQuery is optimization and not premature. It does not have to be optimization of runtime/load time.
Cash is largely a drop-in replacement for jQuery Slim at a significantly smaller size (~6kb vs ~24kb min+gzip).
The methods listed in youmightnotneedjquery.com are a little simplistic/buggy at times and not tested, if you just need a single method from jQuery it would probably be a better idea to simply copy/paste it from Cash.
Last weekend I was trying to find new car dealerships in my region that carried a particular model of car that I'm interested in. They had a dealer search page that could return all dealerships within 250 miles, and they had an inventory search page that had hardcoded the 3 nearest dealership IDs into the URL. But they had no GUI to search all the cars for all the dealers in my region.
I poked around at the elements on the dealership search page, cobbled together a jQuery one-liner to dump all the dealership IDs in my region, and pasted those into the URL to finally see every individual car in my region of the model I wanted. The page took quite a while to load, so probably have have some DoS vulnerabilities to deal with, but at least I was happy.
Vanilla javascript would have been so much more cumbersome!
And AFAIK not matched by any simple wrapper for the newer APIs (it's fashionable to go to heavier ones like axios).
I still grab jQuery into projects for the sheer convenience.
I have actually gone back to making heavier use of jQuery again these days.
The biggest flaw of jQuery is concealing some levels of complexity that are absolutely vital to grasp.
The primary reason for that distinction is that you are willing to spend a tiny bit of effort on micro-improvements to quality of product or aren’t, just like parenting. Yes, the effort is ridiculously tiny because it pays for itself with only a trivial amount of practice.
jQuery speeds up development, but in most situations it's straightforward to replace.
On the other hand, I never remove React (and especially Reagent) from an existing site - too much effort, too much to break.