Hacker News new | ask | show | jobs
by jamiesonbecker 1983 days ago
It's ironic that there's probably no bigger sales pitch for jQuery than this site.

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.

19 comments

I agree this page hasn't aged well, but that's because it's stuck on IE10 as the support level it's targeting. If you don't need to target IE at all (only Edge), then everything becomes simpler. That's not always safe, but that's why you might not need jQuery...

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];
Your fetch examples don't reject the promise if the server responds with error status code, like 404, which is probably not what you'd want. You'd need to handle that separately with something like

    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 know this pattern and have used it myself. The problem is though, that generally you should only throw an error when you reach an exception - it's like saying "I don't know what to do next", and you defer that decision up the stack.

Is a request that technically succeeds (the response has come back), but has a status code where the server has indicated something didn't work always an _exception_ in your client code? I'd argue it isn't, and should just be handled in the normal control flow of your client code via conditionals.

The answer probably depends a lot on what you're used to from other languages.

Java users might want to make 404 an exception (FileNotFoundException), C++ users probably wouldn't throw an exception for that

Nice, thanks for this!
Really thanks, but Android Chromium has support "fetch" too late (2020). Well, I can wait.
You can use a polyfill such as https://github.com/developit/unfetch (500 bytes).
You can use a polyfill such as https://github.com/github/fetch.
I think a lot of the initial appeal around jQuery was that it made querying and manipulating the DOM simple. Much of its features have been replaced by broadly-available APIs like Document.querySelector and Element.classList. 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. I miss relying on jQuery because it's familiar and consistent, but it also makes it easy to forget how much better browsers have gotten in the time since it was introduced.
I thought a big part of the initial sales pitch was not having to deal with cross-browser compatibility issues.
document.querySelector was not available in IE 6 and 7.

Dealing with those versions was where jQuery really earned its spot in the JS universe. It was a lot to remember where all the quirks were and the incantations to work around them.

IE 6. Now that's a name I haven't heard in a long time...
Just patched a problem in a WordPress site due to (now broken) support for IE7 two days ago. The elders of the Internet are still around. ;-)
I'm so sorry. Do you want to talk about it? :P
The longer the better. What a neverending nightmare it was.
Maybe there was more than one big part!
I still think the jQuery API is significantly easier than the DOM one. querySelectorAll() returns this NodeList object that's much harder to use than it needs to be. Things like getting the next sibling is much harder than jQuery's .next(), etc. etc.

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.

With modern JavaScript you can easily cast a NodeList to an Array, e.g. `let spansArray = [...element.querySelectorAll("span")]`.

I find both `element.nextElementSibling` and `element.next()` to be examples of poor API design. The former one is more verbose than needed while the latter one is so short you can't even tell whether it's a method or a property.

> With modern JavaScript you can easily cast a NodeList to an Array, e.g.

Ah, thanks. I got bitten by this recently and didn't know what to do with this "thing that's not an array but seems like it should be, and doesn't always behave like one"

FYI the reason it's not an array is because if you store a reference to it, it will stay up to date as and when the DOM changes.
The NodeList returned by querySelectorAll() is not live. There is really no reason for it to return a NodeList other than backward compatibility.
Before that ES2015 allowed you to do Array.from(nodeList, mapFunc?) which I still use due to the optional mapping function e.g. Array.from(document.querySelectorAll('a'), a => a.href)
If you dislike promises, what do you prefer? Callbacks? Why?
Because it's a lot clearer what gets run in what order.
How? It's about the same if you have one callback maybe, but as soon as you have a callback within a callback - or worse, want to do something involving the results of more than one callback - I just can't see it. What's the advantage of what's often referred to as "callback hell" for you?
As someone that had to handcraft client-side browser experiences in the early 2000's (think drag and drop, elements of single page applications, etc.), I basically had to write two versions of everything in order to support Netscape and IE. It was tremendously interesting because I was building things that you really didn't see out in the wild at the time. It was also tremendously frustrating dealing with DOM and feature differences.

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.

Jquery isn't going anywhere. It might take a few weeks to get a JNR dev up to speed with native dom apis. It'll take a few hours for them to grasp jquery and begin writing working spaghetti in no time at all.

> 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.

We are underselling jquery a little bit. The browsers adopted jquery’s contribution of creating one of the most intuitive ways to deal with DOM/selection. It’s similar to how JSX is probably the most intuitive solution for templating/wiring/composing at the moment, also similar to how two-way binding was incredibly intuitive.

Browsers got to this point because jquery pushed for it.

This comment is a great example of what I call "lines of code mindset" which is form of tip of the iceberg mentality, where programmers optimize for simplicity only the code they see. Is saving 10-15 lines worth it if you need an 86.1 Kb vendor dependency? Hidden complexity you don't control is the most expensive kind I think.
It's 77k for the latest version, and after compression it's ~32k. It's really not all that large. You can also reduce this to about ~27k if you exclude some less-commonly used things like animations, shortcuts, etc.

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?"

There is an additional cost to such a dependency that isn't expressed in bytes.

Javascript/CSS/HTML forms the common basis of web development. You may assume every reader of your code is familiar with it.

If you use a specific library, you are restricting (easy) readability to those that know the specific library.

This has merit if the library provides sufficiently useful abstractions or shortcuts, but it's only a drawback if the library provides merely an alternative way to write something already possible in the base layer.

That's fair, but I also think that JQuery is often judged much more harshly than other libraries that have a significantly higher learning curve.

I know plenty of developers who would view inclusion of JQuery as some cardinal sin due to reasons like the ones you state, but don't apply the same logic to React, Redux, or other more modern, significantly more complex libraries.

I think a lot of that is the "problems they are solving" and "problems they left behind for the developer". JQuery was built to solve "browser compatibility issues" and left behind things like "component structures of code/code organization", "data-flow organization", and more as out of scope.

Browsers have since mostly fixed "browser compatibility issues" at the standards level, so that problem technically no longer needs solving.

As applications have grown larger those other things that were out of scope for JQuery have become bigger and bigger problems that developers face. (Of the big two I mentioned React solves one, Redux solves the other.)

Some people see JQuery as a "cardinal sin" for the first issue: browsers have already "solved" this, this is a deadweight because it fixes a problem I no longer have. They would have fewer problems with React/Redux/whatever because they solve new problems.

Some people see JQuery as a "cardinal sin" as much for the latter issue: because JQuery was so unopinionated on code structure, data flow, component structure, it led to a lot of real world code that was "JQuery spaghetti" littered with anti-practices like relying heavily on global or might as well be global variables for state information, with no structure to which code might impact which variables and when. Componentizing a JQuery system was often a lot of hard work that JQuery itself didn't help with (and given it's own common usage as a window.$ global with sometimes surprising bits of hidden state inside it, in some cases directly hurt those efforts). Given libraries like React or Redux were designed to solve some of the problems that JQuery once created, it also seems clear why some developers might be very vocally antagonistic to JQuery but have no problem bloating a project with tools that solved those problems and/or have more structure and opinions on building "good" componentized/compartmentalized structures.

Not a front-end developer, but could this simply be a generational issue? Every framework invented before my career is a clumsy dinosaur, every framework invented during my career is the silver bullet that will solve all problems...
The size argument against jquery has always dumbfounded me. Bundle sizes in megabytes, "node-modules" folders with thousands of files and hundreds of megabytes are fine for modern web apps, but if you dare to mention jquery, you can bet someone will cry about overhead and waste.
Sites looking to use jQuery most likely aren't doing much more than a few event handlers and an interactive component here or there.

In those cases, I'd argue pReact is superior. It's almost 10x smaller (29kb vs 3.5kb gzipped). It's faster and more structured leading to less maintenance cost and more code reuse. If you use hyperscript, there's also no JSX compilation required.

I'd like to learn about usage of preact with hyperlink or similar. Do you know of a repo I can take a look?
I think that's hard to ascertain because it's a drop-in replacement for react. I assume you mean hyperapp instead of hyperlink.

It gets around a half-million downloads per week according to NPM stats while hyperapp gets under 3k per week.

That's a very good point. We have been hating JQuery for so long, that we didn't notice that it's size when down while app size inflation grew exponentially. 15 years ago loading 50kb of bloat was reason to worry, today no one bats an eye.
I just want to mention that you are replying to someone who never said anything about SPA. They made an interesting point about trade offs.
It describes the general attitude of the community; go to /r/javascript or /r/webdev and mention jQuery (...if you're brave enough) and you'll get those kind of responses, often accompanied that you should be using "modern tools". Then mention multi-megabyte JS bloat and you'll get those kind of responses as well, in the very same thread, and the very same people will be argueing both points at the same time.
While your points might be true, you are arguing how there are hypocritical and dishonest people somewhere else.

You are also putting a heavy burden of proof on your readers: it generally sounds implausible that exactly the same people would complain about <100kiB being bloat and >1MiB not for the same use-case, but I am not going to go and fact-check that (with the implausibility of the claim, I would expect you to give direct pointers yourself or will simply distrust your claim).

You seem to know quite a bit about this, do you know why there isn't some sort of a "compile" phase where the jquery examples wouldn't be translated into the minimum js equivalent? Seems like then you could get the same syntax and minimum size.
You mean translating jQuery to "native JS"? I suppose it's possible, but I don't know if anyone built anything for it.

All I know is that you can build a custom jQuery build with grunt, as described in their README, which is what I do. I mostly use JavaScript as if the last ten years didn't happen, so I'm hardly an expert on any of this :-)

Good point: different JS people have different opinions on tradeoffs.
> Is saving 10-15 lines worth it if you need an 86.1 Kb vendor dependency?

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.

> > Is saving 10-15 lines worth it if you need an 86.1 Kb vendor dependency?

> Yes, absolutely. That's a total no-brainer.

That's what we've been thought but it's not a no brainer at all. Context matters, but you disregard it and only focus on the lines of code, just as the author of the comment you respond to is saying people do.

You're building a marketing page that's not gonna be updated after completed and only gonna be valid for X days? Sure, the code doesn't matter.

You're trying to build a fast and slim UI that's gonna be deployed on routers and possibly loaded on low-power devices? You better care about every single line that gets loaded on the device.

I'm not saying dependencies are always wrong. I'm also not saying it's always right. I'm saying why you need the dependency and the quality of the code it includes is important to consider, and knee-jerk reactions of "of course I'd use it" is hurting the profession more than the library reuse saves us currently.

> You're trying to build a fast and slim UI that's gonna be deployed on routers and possibly loaded on low-power devices? You better care about every single line that gets loaded on the device.

Unless you've gone out of your way to buy a (more expensive) part with less memory, your router will have enough memory to make 86.1Kb an utter irrelevancy; so will most of what were traditionally considered "low-power devices". Yes there are extreme cases where it matters, but we're talking about a vanishingly rare proportion of use cases.

> I'm not saying dependencies are always wrong. I'm also not saying it's always right. I'm saying why you need the dependency and the quality of the code it includes is important to consider, and knee-jerk reactions of "of course I'd use it" is hurting the profession more than the library reuse saves us currently.

I think this is backwards, and the knee-jerk reaction of "of course it's important and you need to carefully think about it" is what's holding back the industry. The overwhelming majority of the time, the right thing is to use the dependency; the best development practice is to default to using dependencies and reassess if and when it you hit an actual problem.

>> Is saving 10-15 lines worth it if you need an 86.1 Kb vendor dependency? >Yes, absolutely. That's a total no-brainer.

I'm curious - would you be able to elaborate, please? Thank you.

Assuming I'm going to need the complexity more than 1-2 times in my source code, I'm going to be writing my own abstraction. Which takes time, needs tests writing, and I am going to make a typo or other silly mistake somewhere.

Run into a couple of examples of such complexity, and the dependency is well worthwhile.

A jQuery that can be tree-shaken would be awesome, as there are parts I use regularly and others I have never used. Ironically the -lite bundle leaves outs parts I use frequently...

Just look at the cost-benefit. Typically internal code has a defect rate of around 1/1000 lines, so 10-15 lines is about 0.01 bugs. 86.1Kb of an established, widely used library is a cost that I can't meaningfully distinguish from zero.
> Hidden complexity you don't control is the most expensive kind I think.

That's called encapsulation. :)

Seriously, encapsulating complexity is the foundation of most programming paradigms.

In the real world, it turns out that code you didn't write can also have bugs or not behave as you expect it to, so the less of that there is, the better.

Encapsulation/abstraction should really be a tool of last resort. From experience, it doesn't actually help reduce complexity if overused, but just makes it hidden and more likely to surprise you when you're debugging.

> In the real world, it turns out that code you didn't write can also have bugs or not behave as you expect it to, so the less of that there is, the better.

jQuery's not a very good example of this though. It's one of the most widely used, and hence most tested and least buggy pieces of software out there. Nowadays the web APIs are pretty solid, but back in the IE6/7/8 days the jQuery API was a lot less buggy than using the built in APIs directly.

Have fun implementing everything from scratch in assembly.
> In the real world... From experience...

Does jQuery (est. 2006) have more bugs in it than your code?

As has been seen many times recently third party libraries are a major attack vector for the bad guys.
> In the real world, it turns out that code you didn't write can also have bugs or not behave as you expect it to

To me this seems a comment that only stands for one-developer projects.

Actually, it's called abstraction, as a technical point.
Good point. This is what I was referring to:

https://en.wikipedia.org/wiki/Encapsulation_(computer_progra...

It's never just 10-15 lines, and I'll always take 86Kb of a properly tested, production environment validated, properly documented, community supported, cross-browser library over the one-off functions I frequently squash in code reviews.
>is saving 10-15 lines worth it if you need an 86.1 Kb vendor dependency?

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.

Lines of code is a bad metric for complexity.

Jquery is a thin wrapper over javascript, whereas React has a comparable size but is a significantly higher level abstraction.

> Is saving 10-15 lines worth it if you need an 86.1 Kb vendor dependency?

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.

A vendor dependency that's almost certainly locally cached already if you use one of the common CDNs for serving jQuery - ajax.googleapis.com, cod.jquery.com, cdnjs.cloudflare.com or cdn.jsdelivr.net.
Browsers are now separating out caches per origin so that benefit has gone away.
I doubt the “choose not to use jQuery” path means “never write a function to wrap up that boilerplate”. The point is that you might be able to write the equivalent function instead of pulling down a whole library.

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.

jQuery is immune to modern optimisation techniques such as three shaking (only including the modules actually used) because it’s fluent interface makes it a gorilla that holds quite a few bananas, even if you only need one of the bananas.
I would imagine the percentage of front end projects that have a build chain sophisticated enough that tree shaking is important and where 30 KB has a significant impact on their bundle size is vanishingly small.
Tree-shaking isn't a sophisticated feature with ES2015 modules and it's more surprising today when build chains don't support it. (The sophisticated features come into play doing any sort of tree-shaking on older module types such as CommonJS or UMD.)

It's not even a build-chain only feature at this point. Some of the reasons the ES2015 module format was built the way that it was were exactly so that browsers can do their own tree-shaking of runtime code. Even if you don't save on the performance impact of the extra 30 KB from being downloaded, in modern enough browsers you would potentially still see a performance impact on browser memory usage and JIT compilation time.

Even if your bundle size has bloated to a MB already, a 30 KB savings is still roughly a 3.3% savings. It's still noticeable. Whether that is "significant" is an argument of personal taste and how many "9s of performance" you try to deliver. Even single digit percentage savings can be huge "significant" wins for many projects.

I generally agree but I think the site is specifically calling out use of jQuery in libraries to avoid a big dependency.

"If you're developing a library on the other hand, please take a moment to consider if you actually need jQuery as a dependency"

Agreed! Especially for a smaller library or one that wouldn't adequately take advantage of jQuery shortcuts (or if you're using another library for DOM/shadow DOM, like react/angular/vue/etc)

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.

> In every single example, the jQuery version is basically one or two lines of code, versus 10-15 lines for the alternative.

"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."

Also, most of the more complex examples have single-liner equivalents in modern browsers.

This page is just outdated. IE10 is a now deprecated browser whose last release was 4 years ago according to Wikipedia.

Have you considered some alternatives? I made a 3kb one back in the day (https://umbrellajs.com/) and there are others like Zepto that don't need to deal with the baggage of IE and old browser APIs and still give you the niceties of jQuery.
Very nice, and great site design too.

(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.)

Thanks! But jQuery has not really moved over, compare "addClass" in jQuery vs UmbrellaJS:

- Umbrella 6 lines (max col 55): https://github.com/franciscop/umbrella/blob/master/src/plugi...

- jQuery 35 lines (max col 83): https://github.com/jquery/jquery/blob/master/src/attributes/...

Yes I reuse methods there to make my life easier like `.eacharg()`, but jQuery as well with `getClass()`. The difference is that UmbrellaJS is using the native `classList.add`, while jQuery is doing string concatenation and cleaning it up heavily. jQuery does not even use `className`, it uses the even older `.setAttribute()`.

Why they cannot just move over? I did try to move them over, the thing is that the edge cases of jQuery were solidified into features as people found them and wrote tests. And jQuery is very big on not breaking behaviour even for small things, so the only way to maintain the current exact behaviour is to have the current exact code, hence you cannot just migrate it over.

> jQuery is very big on not breaking behaviour even for small things

You answered your own question :)

Yes the "Why they cannot just move over?" was a rhetorical question since I was just explaining that. The larger point being that jQuery being still stuck in doing things manually is detrimental, hence devs could/should consider small modern alternatives even if they want an API similar to jQuery.
I've never stopped using jQuery, it makes everything so much easier to work with. I've built large web apps using only jQuery and never had any problems, I just really like direct DOM manipulation instead of some abstractions and jQuery makes it as simple as possible.
It says you _might_ not need it not that you will _never_ need it. I have used the page when I'm trying to do something and would need jquery for one small thing. I don't want to use a library for one thing so 10-15 lines of code instead of all of jquery is a good tradeoff in those cases.
This is all very old javascript to be fair, the modern equivalents are as terse as jquery these days.
Somewhat true, but this was also old jQuery :)

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")
Maybe a nit, but these aren't equivalent. The jQuery version will apply it to all elements that match your selector, where the ES6 version will only apply to the first matching element.

Equivalent code in ES6 would be (maybe there's a terser way but this is what I'd do at first glance):

    [...document.querySelectorAll('.className')].forEach(el => el.classList.add('darktheme'));
Not a whole lot extra in terms of actual code, but I'd argue it's not super intuitive (having to cast a NodeList to an array is a pretty big beginner footgun), and as you get into more complex scenarios, the jQuery architectural pattern of operating against collections of nodes really shines.
You can use forEach without the splat:

    document.querySelectorAll(".className").forEach(el => el.classList.add('newClass'));
Still doesn't seem like much of a win compared to the jQuery :)

    $(".classname").addClass("darktheme")
NodeLists should have a forEach method as far as I know
There are quite a few more examples of this:

    $('.class').remove()
    $('.class').after(...)
vs:

    var e = document.querySelector('.class')
    e.parentNode.removeChild(e)

    document.querySelector('.class').insertAdjacentElement('afterend', ...)
This is good example of how browser APIs have gotten better:

// Edge 12 document.querySelector('.class').remove();

// Edge 17 document.querySelector('.class').after(...);

Where jQuery shines - but also hides a lot of complexity- is when operating on an array of elements, e.g. if you want to remove all elements with a certain class.

This kind of code grows explosively in a moderately-sized project, and the sheer volume and verbosity makes it hard to debug. Not to mention requiring more tylenol ;)
The modern DOM equivalent would look almost the same as the jQuery version:

  document.querySelector(".class").remove();
  document.querySelector(".class").after(...);
Agree. Even before getting into things like: $(".classname").closest(".container").addClass("active”);

I do not get the hate over jquery, specially since frameworks like angular used (use?) to include a light version of it (sizzle or similar?) and methods like $httpParamSerializerJQLike, which does not scream of elegance.

I still remember when prototype.js was the default in rails, and jquery was so less overengineered and it just worked. It felt like magic.

The opinions mostly depend on what people know. The dvorak keyboard might be better?
Yes but the former will silently fail on you. Good luck finding that!
This is probably a feature. The non-jquery version will need a check for the elements existance to not blow up, which could the same be added to the jquery version for error reporting.

Plus, in this case, you will find out by seeing the dark theme is not active :p

I think this misses the point, which is called out directly at the top of the site:

"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).

> In every single example, the jQuery version is basically one or two lines of code, versus 10-15 lines for the alternative

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.

I've done this before - you just end up rewriting jQuery hehe.
You'd end up writing a subset of jQuery that only has the parts you need and skips those where you almost wouldn't gain anything.
Well, except that jQuery and a number of third parties have already extracted or ported various subsets of jQuery and have packaged it already for easy integration.
That's a good solution if you need such a subset. But maybe you need just a single function.

And maybe such a single function is currently already provided by the browser APIs.

Or maybe there are packages of individual functions of JQuery? But that would serve little purpose IF the functionality is provided by current browsers.

In any case I think the article serves a good purpose in explaining what are the most useful parts of JQuery and how you could implement them yourself with the more modern browsers if and when you need them.

My preference is to avoid dependencies if I can and prefer depending on my own code which uses standard APIs if possible.

Over time you end up adding just about everything back in as the app grows... But worse!
Probably not for any given single app. Some apps need more JQuery-like functionality some less
But if I need to wrap around everything, I might was well just use jQuery.
> 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.

Your app becomes smaller and easier to maintain and understand because it has fewer dependencies.

Of course if you need much of the functionality of JQuery then it is a perfect fit for you.

Note there is a cost to JQuery associated with learning and understanding what exactly each function of its API does. If you have paid that cost already by using JQuery and thus learning it, and you need it, then it makes sense to keep on using it.

I would prefer web developers accepted they need to write a few hundred lines of 'ugly' vanilla JS to drive their website than they include a 30KB library that they only really use 0.2KB of.

On the web, user experience should really be a higher priority than developer experience.

Hundreds of lines of ugly vanilla JS which duplicate jQuery features which aren't as well tested and probably don't handle all the edge cases.

> 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.

If you're not seeing jQuery - as with every third party library - as something that now needs a mitigation plan in case it ever vanishes, and a security monitoring process to keep up upgraded, you're doing it wrong.
Why do I need a migration plan? I have jquery.js saved on my disk; that's never going to vanish, and it's not going to stop working if upstream decides to stop supporting it. And if I discover a bug then I can just fix it myself, just like any code saved on my disk.

jQuery rarely has security issues anyway; and the issues that do exist are usually low-impact. It certainly won't have any more than any code I'll write myself.

You just have to chose the right tool for the job and the limitations. You get something in return for doing the extra work and you get something in return for glue coding some libs. Also keep an eye on the experience points.
If your website has two non thumbnail images in it, the 30KB library is gonna become a rounding error in the load time
if the 30KB library is already cached because everyone else is using it too, then isn't it technically smaller than however many hundreds of lines of code you had to custobuild?
Most modern browsers don't really have global caches any more, and it's now all partitioned per-origin.

I do agree 30k is hardly worth thinking about.

I think they are referring to loading it from a global CDN.
Thanks, I didn't know that!
jQuery, minified and Gzipped is 30.4kb. That's completely unacceptable for my needs. This is why folks complain about bloat.
Are you being sarcastic?

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.

May or may not be. I deal with a not small amount of customers that are on extremely slow connections where 30k less makes a big difference. You can do a lot in 30k. jQuery makes life a heck of a lot easier though.
I think this is a fair point if you genuinely want to keep your bundle size as small as possible. Many times, the people complaining about jQuery's size are serving 2 MB bundles. 30K is immaterial in that scenario.
Like I mentioned in another response, my bundle was 200k. 30k would have been significant bloat.
I'm absolutely NOT being sarcastic. In my time at Overstock, I prided myself on a mobile-first bundle that was 200k... for the ENTIRE app. The time to first meaningful paint and time to interactivity were fantastic. This was especially true for 3G and emerging markets. There is NO WAY, I'd add 30k so I could select/iterate DOM elements. I simply see that library (as well as a few other common ones) as part of the problem we see in JS development.
He might not be being sarcastic, servers are expensive and every little slice helps, though I think the cdn aspect changes this question somewhat.
It's a serious hurdle when pReact is only 10kb unzipped (13kb with hooks) while jQuery is 89kb.

Accounting for 70% average minification and 40 characters per line on average, that's around 6,500 lines of normal code shipped "for free" by using pReact instead where there's both no wire cost and no extra parse time.

Agree with this. Fancy libraries like React/Vue etc are great, but they require more human resources in terms of development and add more complexity to your development cycles. I am working on a side project and initially got tempted to use Vue for the front-end but once I stepped back and re-thought about it, jQuery was a no-brainer in terms of how much I can achieve in the time I have.
Why do jQuery at all now? IE 11 is no longer supported. All major browsers are evergreen and, except for some small edge cases that jQuery didn't really support anyways, they are pretty much completely unified in the APIs they support. If you are really worried about that 1% difference, then you can use tools like babel to cover those cases.

The only reason to reach for jQuery, IMO, is familiarity. If you don't want a framework, then just write vanilla js.

Worth noting is that at least in the animation case, the non-jQuery (CSS) version should perform better than the jQuery version
Are you sure? AFAIR, jQuery has used native (hardware-accelerated) CSS transforms since 2014.
At least in the example on this page, it performs .fadeOut() by changing the opacity via JavaScript instead of using the CSS transition property. You can verify by inspecting the DOM

https://api.jquery.com/fadeOut/

Edit: I just realized you said "transforms". Transforms are a separate question from transitions. CSS transforms are concerned with giving an element a different size, rotation, and/or position. Transitions are concerned with changing any given CSS property gradually over time (including potentially transforms). I think you're right that jQuery started using CSS transforms, but it does not appear to use CSS transitions.

Edit: I partly misspoke. I assumed CSS transitions would be nontrivially more performant since it's a more declarative API and the math would be done natively by the browser, but according to MDN the performance difference is negligible in most (though not all) cases if you're using requestAnimationFrame in the JavaScript version: https://developer.mozilla.org/en-US/docs/Web/Performance/CSS...

The main case where CSS transitions are meaningfully faster appears to actually be transforms themselves, because for those the actual transition, too, can be moved to the GPU, whereas a JavaScript-driven transition still has to be run on the main CPU thread.

Fair point. Thanks for bringing it up!
Assuming you meant "CSS Transitions": No, jQuery uses requestAnimationFrame.

* "CSS transforms" are unrelated to animations.

I haven't gone this far, but I still like lodash. It feels like it fleshes out a too-light core JS lib.
agree, i think this page has a lot of value in explaining how jquery works which is very valuable for beginners, need a more accurate title i guess
youmightneedtoreadtheintro