Settings

Theme

You might not need jQuery (2014)

youmightnotneedjquery.com

166 points by lemonspat 5 years ago · 240 comments

Reader

jamiesonbecker 5 years 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.

  • domenicd 5 years ago

    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];
    • inbx0 5 years ago

      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.

      • Wintamute 5 years ago

        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.

        • unilynx 5 years ago

          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

    • jamiesonbecker 5 years ago

      Nice, thanks for this!

    • mdtrooper 5 years ago

      Really thanks, but Android Chromium has support "fetch" too late (2020). Well, I can wait.

  • bichiliad 5 years ago

    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.

    • cosmotic 5 years ago

      I thought a big part of the initial sales pitch was not having to deal with cross-browser compatibility issues.

      • jrumbut 5 years ago

        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.

        • codeisawesome 5 years ago

          IE 6. Now that's a name I haven't heard in a long time...

          • martin_a 5 years ago

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

            • spicybright 5 years ago

              I'm so sorry. Do you want to talk about it? :P

              • martin_a 5 years ago

                I'm not sure. It was kind of traumatic, but on the other hand it's a very old site, so it was obvious that there might be some dead bodies in the basement. Found one, ignored the others.

                • jrumbut 5 years ago

                  The IE 7 compatibility code broke the site in modern browsers, or did you really get a visitor on a Windows 98 machine?

                  • martin_a 5 years ago

                    It was a bug in an old version of superfish.js which relied on a deprecated jQuery function to detect the browser. $.browser broke in the new(er/est) version of jQuery which is integrated in that site.

          • user3939382 5 years ago

            The longer the better. What a neverending nightmare it was.

      • np_tedious 5 years ago

        Maybe there was more than one big part!

    • arp242 5 years ago

      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.

      • jarek-foksa 5 years ago

        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.

        • porker 5 years ago

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

          • nicoburns 5 years ago

            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.

            • jarek-foksa 5 years ago

              The NodeList returned by querySelectorAll() is not live. There is really no reason for it to return a NodeList other than backward compatibility.

          • spiralx 5 years ago

            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)

      • names_are_hard 5 years ago

        If you dislike promises, what do you prefer? Callbacks? Why?

        • arp242 5 years ago

          Because it's a lot clearer what gets run in what order.

          • spiralx 5 years ago

            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?

    • fatnoah 5 years ago

      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.

    • vagrantJin 5 years ago

      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.

    • runawaybottle 5 years ago

      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.

  • jart 5 years ago

    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.

    • arp242 5 years ago

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

      • tomtomtom777 5 years ago

        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.

        • ryanbrunner 5 years ago

          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.

          • WorldMaker 5 years ago

            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.

          • Viliam1234 5 years ago

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

      • mad182 5 years ago

        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.

        • hajile 5 years ago

          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.

      • toper-centage 5 years ago

        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.

      • varrock 5 years ago

        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.

        • arp242 5 years ago

          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.

          • necovek 5 years ago

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

      • braveyellowtoad 5 years ago

        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.

        • arp242 5 years ago

          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 :-)

      • robertlagrant 5 years ago

        Good point: different JS people have different opinions on tradeoffs.

    • lmm 5 years ago

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

      • capableweb 5 years ago

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

        • lmm 5 years ago

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

      • petecooper 5 years ago

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

        • porker 5 years ago

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

        • lmm 5 years ago

          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.

    • jamiesonbecker 5 years ago

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

      • userbinator 5 years ago

        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.

        • nicoburns 5 years ago

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

        • scubbo 5 years ago

          Have fun implementing everything from scratch in assembly.

        • jamiesonbecker 5 years ago

          > In the real world... From experience...

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

        • quattrofan 5 years ago

          As has been seen many times recently third party libraries are a major attack vector for the bad guys.

        • donapieppo 5 years ago

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

      • franklyt 5 years ago

        Actually, it's called abstraction, as a technical point.

    • notjustanymike 5 years ago

      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.

    • bryanrasmussen 5 years ago

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

    • viseztrance 5 years ago

      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.

    • nickjj 5 years ago

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

    • spiralx 5 years ago

      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.

      • M2Ys4U 5 years ago

        Browsers are now separating out caches per origin so that benefit has gone away.

  • eyelidlessness 5 years ago

    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.

    • graftak 5 years ago

      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.

      • ryanbrunner 5 years ago

        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.

        • WorldMaker 5 years ago

          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.

  • Zaheer 5 years ago

    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"

    • jamiesonbecker 5 years ago

      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.

  • heleninboodler 5 years ago

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

    • ratww 5 years ago

      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.

  • franciscop 5 years ago

    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.

    • skynet-9000 5 years ago

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

      • franciscop 5 years ago

        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.

        • jamiesonbecker 5 years ago

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

          You answered your own question :)

          • franciscop 5 years ago

            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.

  • pkorzeniewski 5 years ago

    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.

  • jccalhoun 5 years ago

    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.

  • peanut_worm 5 years ago

    This is all very old javascript to be fair, the modern equivalents are as terse as jquery these days.

    • jamiesonbecker 5 years ago

      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")
      • ryanbrunner 5 years ago

        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.
        • ratww 5 years ago

          You can use forEach without the splat:

              document.querySelectorAll(".className").forEach(el => el.classList.add('newClass'));
          • jamiesonbecker 5 years ago

            Still doesn't seem like much of a win compared to the jQuery :)

                $(".classname").addClass("darktheme")
        • peanut_worm 5 years ago

          NodeLists should have a forEach method as far as I know

      • arp242 5 years ago

        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', ...)
        • realityking 5 years ago

          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.

        • jamiesonbecker 5 years ago

          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 ;)

        • jarek-foksa 5 years ago

          The modern DOM equivalent would look almost the same as the jQuery version:

            document.querySelector(".class").remove();
            document.querySelector(".class").after(...);
      • mejutoco 5 years ago

        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.

        • 6510 5 years ago

          The opinions mostly depend on what people know. The dvorak keyboard might be better?

      • asiando 5 years ago

        Yes but the former will silently fail on you. Good luck finding that!

        • mejutoco 5 years ago

          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

  • HiJon89 5 years ago

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

  • galaxyLogic 5 years ago

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

    • catmanjan 5 years ago

      I've done this before - you just end up rewriting jQuery hehe.

      • DarkWiiPlayer 5 years ago

        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.

        • 3131s 5 years ago

          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.

          • galaxyLogic 5 years ago

            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.

        • catmanjan 5 years ago

          Over time you end up adding just about everything back in as the app grows... But worse!

          • galaxyLogic 5 years ago

            Probably not for any given single app. Some apps need more JQuery-like functionality some less

    • mschuetz 5 years ago

      But if I need to wrap around everything, I might was well just use jQuery.

    • cheph 5 years ago

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

      • galaxyLogic 5 years ago

        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.

  • onion2k 5 years ago

    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.

    • arp242 5 years ago

      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.

      • robertlagrant 5 years ago

        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.

        • arp242 5 years ago

          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.

      • 6510 5 years ago

        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.

    • Dudeman112 5 years ago

      If your website has two non thumbnail images in it, the 30KB library is gonna become a rounding error in the load time

    • dylan604 5 years ago

      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?

  • nobleach 5 years ago

    jQuery, minified and Gzipped is 30.4kb. That's completely unacceptable for my needs. This is why folks complain about bloat.

    • jamiesonbecker 5 years ago

      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.

      • zhte415 5 years ago

        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.

        • ryanbrunner 5 years ago

          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.

          • nobleach 5 years ago

            Like I mentioned in another response, my bundle was 200k. 30k would have been significant bloat.

      • nobleach 5 years ago

        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.

      • franklyt 5 years ago

        He might not be being sarcastic, servers are expensive and every little slice helps, though I think the cdn aspect changes this question somewhat.

      • hajile 5 years ago

        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.

  • princevegeta89 5 years ago

    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.

    • cogman10 5 years ago

      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.

  • brundolf 5 years ago

    Worth noting is that at least in the animation case, the non-jQuery (CSS) version should perform better than the jQuery version

    • jamiesonbecker 5 years ago

      Are you sure? AFAIR, jQuery has used native (hardware-accelerated) CSS transforms since 2014.

      • brundolf 5 years ago

        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.

        • brundolf 5 years ago

          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.

        • jamiesonbecker 5 years ago

          Fair point. Thanks for bringing it up!

      • asiando 5 years ago

        Assuming you meant "CSS Transitions": No, jQuery uses requestAnimationFrame.

        * "CSS transforms" are unrelated to animations.

  • franklyt 5 years ago

    I haven't gone this far, but I still like lodash. It feels like it fleshes out a too-light core JS lib.

  • slmjkdbtl 5 years ago

    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

  • combatentropy 5 years ago

    youmightneedtoreadtheintro

franciscop 5 years ago

I made Umbrella JS back in the day, a 3kb alternative to jQuery born from the question: You might not need jQuery, then what do you need?

https://umbrellajs.com/

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.

cocktailpeanuts 5 years ago

What we need in 2021 is not this site, it's a youmightnotneedreact.com

  • inopinatus 5 years ago

    I've got a toolkit of pure CSS widgets I privately call "You might not need Javascript". Dropdowns, modal/lightbox, concertina, slideovers, toggles, popover, transitions, no problem.

    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.

    • marlowe221 5 years ago

      As new web developer, I would LOVE to learn how to do this kind of thing purely in CSS!

      • inopinatus 5 years ago

        My process:

        * trial

        * error

        * reading the HTML, DOM, and CSS standards documents very thoroughly end-to-end

        * stackoverflow

        * repeat

  • jjcm 5 years ago

    I would say that this corollary would only be possible once webcomponents have form support in all browsers. In my opinion this is the last major hurdle before there is a native alternative for reusable components in the browser. Firefox is working on it[1] but there's no current roadmap for the work for Safari (though the initial form element proposal was well received by their team).

    [1] https://bugzilla.mozilla.org/show_bug.cgi?id=1552313

    • ratww 5 years ago

      I don't think it will replace React, honestly.

      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)!

      • preommr 5 years ago

        We need a better term for front-end-js-frameworks than to keep typing react/vue, or variations of it like react/vue/angular, react/vue/svelte, react/vue/angular/svelte,

    • deergomoo 5 years ago

      The Shadow DOM spec always seemed like a good idea poorly implemented to me.

      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.

  • jonny383 5 years ago

    And of course in 2021 you could build the site using Vue with GraphQL and a CDN deployment pipeline with auto scaling :)

  • ritchiea 5 years ago

    Doesn't everyone know you don't need React? That it's a choice?

    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.

  • adriancooney 5 years ago

    Even better: youmightnotneedjavascript.com

    (and no, I don't mean WebAssembly - bring back static websites!)

halis 5 years ago

Having used react and redux for several years now, I'm a bit burnt out on how bloated and silly the entire front end has become. If I could decide for myself, I probably would use raw DOM or jQuery at this point.

  • RobertKerans 5 years ago

    "has become"? So will you be using Backbone + Marionette, or one of the other MVC frameworks? Which jQuery plugins will you be needing? Will you be using Require.js, or are you just going to have a big list of script tags? What about Bower? What about backwards compatibility and dependency management and other really boring things? If you have a very simple client that "just" uses the DOM APIs or an abstraction over a subset of those (ie jQuery), where have you shifted the complexity to?

    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.

    • zamadatix 5 years ago

      As for "has become" there was a time when it was accepted there were things you didn't do in a browser and it was generally whatever the browser didn't support. If you wanted to do something real wild you'd use some app delivery plugin (java/flash/etc) which just happened to display in the page but that was the extent of involving the browser. Then browsers started supporting some of these abilities natively in response and complexity exploded to try to patch what the browsers shipped with at the time vs what people wanted in total resulting in many tools/libraries/frameworks to deal with the gap. Now the out of the box environment isn't very limited or fractured for the majority of use cases and so we have the option to go back to the simple era where "I can just use what's in the browser" again for most things, except now that generally covers whatever we want to make not "what a webpage should be" like it used to.

  • austincheney 5 years ago

    You have to consider the audience.

    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.

  • joshxyz 5 years ago

    I did the following, still comfy with react.

    - 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

    • finiteseries 5 years ago

      I haven’t used react since 2017, but the fact that react-router is still undergoing painful API changes somehow doesn’t surprise me.

    • idkwhoiam 5 years ago

      How did you replace Material UI with Tailwind? You mean you reimplemented all the components it ships with?

      • joshxyz 5 years ago

        Well that's just impossible. What I just noticed was that when I looked deeper on MUI components, their internals are bulky and almost always used a mixed of JS & CSS instead of just CSS. They even import an external library for their styling.

        On low-end devices it's a bit too much (I'm talking about edge-case users with phones as cheap as $50). It was also quite a chore keeping up with their API changes every couple months.

        I forced myself to cut down on components and just style my UI with CSS. It's more consistent, more predictable, and less strain on the end-user's device. It's a trade-off across looking good, better end-user performance, good user experience, good developer experience, and having more time for the product and users instead of maintaining and updating dependencies.

  • ratww 5 years ago

    I think it really depends on the size and type of the app.

    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.

  • acemarke 5 years ago

    Hi, I'm a Redux maintainer. Please note that "modern Redux" code is very different than what most older tutorials show. We've introduced newer APIs like Redux Toolkit, which is a set of utilities that provide a light abstraction to simplify the most common Redux tasks, and the React-Redux hooks API, which is generally easier to use than the traditional `connect` API.

    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

    [2] https://redux.js.org/style-guide/style-guide

    • wilsonrocks 5 years ago

      I've tried redux toolkit in production and it is a lot better... But I still wouldn't choose redux on balance.

  • qudat 5 years ago

    This might be interesting to you: https://github.com/alpinejs/alpine/

  • leetrout 5 years ago

    There really isn’t a good middle ground yet.

    Look at svelte if you haven’t.

  • mhd 5 years ago

    But think of the react video course makers and router re-implementors!

nate 5 years ago

I miss jQuery. It's funny that an argument against jQuery is "oh, but you have to load that big thing to access your site", but then we'll create Single Page Apps that then proceed to spend loading json for 10 seconds before we start interacting with them. :)

  • schwartzworld 5 years ago

    The techniques listed in that website aren't really used for single-page apps.

    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.

abiogenesis 5 years ago

Now only if someone could combine the snippets on the right hand side in an easy-to-use library.

Oh wait...

  • krapp 5 years ago

    no no no... what we need to do is break them down so that each line is a separate library composed of a single function with its own independent dependency tree and test suite, then build another library out of that, all written in a language that compiles to javascript, and publish it to a proprietary package manager.

    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?

    • quickthrower2 5 years ago

      Then i would only consider it if it has an @types package I can pull

    • emptyparadise 5 years ago

      Code golf, except it's maximizing potential security issues.

    • 6510 5 years ago

      I like the functions (that were suppose to do things) calling functions suffering from the same issue.

      We're not in kansas anymore.

human 5 years ago

I’d be careful about premature optimization. If you can write your code 2x faster by using jQuery, by all means do it. Eventually, if needed, you could rewrite your JS to be free of jQuery, but it would not be a priority for me. Dev speed if more important than load speed for me.

  • austincheney 5 years ago

    That’s not premature optimization:

    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.

    • glckr 5 years ago

      > If your code can execute 10x faster without jQuery then the optimization is not premature.

      One could argue that it is premature if the code doesn't _need_ to run 10x faster.

      • austincheney 5 years ago

        One could also argue that driving to work is premature if you have two perfectly good legs. All ridiculousness aside a person can invent any absurd excuse to hide from the common practices of their profession.

    • ozim 5 years ago

      "optimization - an act, process, or methodology of making something (such as a design, system, or decision) as fully perfect, functional, or effective as possible"

      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.

  • abiogenesis 5 years ago

    What we need is a Jquery-to-VanillaJS transpiler.

    • paxys 5 years ago

      Uh, what do you think jQuery is written in?

      • abiogenesis 5 years ago

        jQuery is written in JS, but if your code is using jQuery functions you are not writing "vanilla JS" anymore. Otherwise we wouldn't need the term "vanilla JS".

        What I meant was inlining the jQuery calls to their equivalent JS snippets, removing the need for including a 80K library if you are not overly dependent on jQuery. It was also a tongue-in-cheek comment.

      • noisem4ker 5 years ago

        The point is doing the translation on the server.

fabiospampinato 5 years ago

I'd suggest to anybody wanting a thin wrapper over the DOM to just go with Cash [1] instead, which I maintain.

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.

[1]: https://github.com/fabiospampinato/cash

_slyo 5 years ago

jQuery is fantastic. I am not a web programmer by trade, but I can always get busy with jQuery and just a couple of Google searches.

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!

fergie 5 years ago

Haven't used jQuery in years. This page is encouraging me to give it a whirl again.

Mooty 5 years ago

No one mentions the fact that jQuery is still used in Wordpress (33% of all websites) everywhere and (as far as I know) in the last theme version they provided this year. Which makes it somehow the biggest library around in terms of usage. I'm still confused why people needs node/react or vue to achieve simple thing that back in the days where pretty easy to do with basic php/jquery. Simplicity in coding was better at the time.

  • KptMarchewa 5 years ago

    The raw count of websites, aka copies of code sitting on some server means nothing, and is bad metric. What matters, is either website view count, or some metric of developer time spend on developing those websites.

porker 5 years ago

And yet, jQuery's AJAX related methods are more convenient than the native fetch() API.

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.

DangerousPie 5 years ago

I bought into this a few years ago and ended up regretting it. My code has become much harder to maintain and read due to all the extra boilerplate code, and it probably has hidden bugs and compatibility issues that I'm not even aware of. And for some things I still ended up requiring jQuery, because they just weren't feasible to do in vanilla JS.

I have actually gone back to making heavier use of jQuery again these days.

  • kebman 5 years ago

    I guess the irony is that jQuery is indeed written in JavaScript, so whatever you set out to do is still "feasible to do in vanilla JS." With that said the main difference is of course that there's far more people involved in maintaining jQuery than there is on most people's individual codebases. Personally I try to make do without it, if nothing else than because it forces me to learn JavaScript better.

    • DangerousPie 5 years ago

      Of course - what I was trying to say there was that it was not feasible without writing hundreds of lines of extra code, with all the development and maintenance cost that brings. In some use cases that trade-off may make sense, but in mine it doesn't.

jojobas 5 years ago

The biggest benefit of jQuery is concealing some levels of complexity that are somewhat hard to grasp.

The biggest flaw of jQuery is concealing some levels of complexity that are absolutely vital to grasp.

dang 5 years ago

Discussed at the time: https://news.ycombinator.com/item?id=7152068

barnaclejive 5 years ago

Someone should make a youmightnotneedspringboot.com

  • nobleach 5 years ago

    Well sure, you could do so much better with a small library like Vert.x (which I love). But getting an entire app framework with config/routing/db connectivity/etc is just so easy with Spring Boot. Plus, you get a vast ecosystem. Now the memory usage and compile times? Yeah, youmightnotneedspringsmemoryoverhead.

    • ironmagma 5 years ago

      If someone can buy this argument but not then immediately understand why a library like jQuery or React is popular, that’s a shame. It’s the exact same reasons: maturity, flexibility, and community/precedent.

      • nobleach 5 years ago

        It's basically a hard no from me on adding a dependency that buys me next to nothing, and bloats my payload to a customers/users mobile device. In that industry, every byte counts. In backend Java/Kotlin apps? I can pay the extra money for memory usage. I cannot ask my users to do the same.

        • ironmagma 5 years ago

          Bundlers these days are very good. Any code that isn’t used is removed with tree shaking/dead code elimination, and React can be swapped with Preact which has a lot smaller bundle size as well.

  • dehrmann 5 years ago

    I'm less interested in what people are running their backend on because that tends not to be where performance issues with sites lie.

    • gt565k 5 years ago

      WHAT? That's exactly where performance issues come from. Chances that the client side code is so poor the site doesn't load is very low.

      • dehrmann 5 years ago

        I mean that it's not usually the language or the framework, but what overall interactions look like. If static HTML loads slowly, yes, it's the backend, but that's not what most sites look like these days; they're rich, client-side apps making lots of API and resource requests, not to mention overhead something like React adds.

      • yashap 5 years ago

        It’s extremely app-dependent. For example, lots of heavy analytics, data crunching type apps can easily have multi-second (or longer) backend requests. For these, the BE tends to dominate perf issues.

        However, for your standard CRUD type app, honestly round trips of 100-200 ms for backend requests are really common/standard. On the FE, loading and evaluating big JS bundles, rendering, etc., can be way slower. For CRUD apps I’ve worked on, perf issues on the FE have been more common than on the BE. Especially with the common React/Redux stack, it’s very easy to make perforce mistakes and end up with a lot of unnecessary component updates when things aren’t really changing.

hathym 5 years ago

The first example alone (3 lines vs 18) convinced me that I still need jQuery.

donutdan4114 5 years ago

jQuery 3+ minified is 31Kb.... Wtf is the problem with that? Can we just admit that vanilla JS is not ideal and having some abstraction (and tiny bit of page load) is worth it? I am not building web apps that are primary used in Sudan with 1G connection. 31Kb is practically nothing. THIS image is larger than that! http://content.cdn.viber.com/stickers/144/10400/00010400.png

  • austincheney 5 years ago

    JQuery is orders of magnitude slower than vanilla JS. It’s not about download time but execution time. I am not deliberately trying to punish my users.

    • motogpjimbo 5 years ago

      Do you use React? In my experience, people arguing against jQuery are usually simultaneously arguing for React as a replacement for it, and are therefore arguing for replacing a ~30kb library with multi-megabyte bundles of catastrophically broken SPA code.

      • iaml 5 years ago

        Why do you think you can only write multi-megabyte apps with react? And why do you think those two are the only options? You can write decently sized react code that's 300-500 kb bundled and if you're not ok with that you can start dynamically loading dependecies. Companies just choose to not spend any time optimizing it.

      • austincheney 5 years ago

        I do not, but Angular is worse. Last I looked it’s a 300mb download after installing the npm dependencies.

austincheney 5 years ago

The need for convenience libraries is like parenting with television. It doesn’t seem bad and is just so much easier in every possible way, but any objective observer readily sees the difference in quality of product.

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.

  • ant6n 5 years ago

    Not sure whether the comparison is apt. Especially during the lock down, parenting without using Media ... well, it does not involve a „trivial“ amount of practice or a „ridiculously tiny“ amount of effort.

m1kal 5 years ago

It's funny this site doesn't mention dialog - the only feature I'm using that is hard to replace by vanilla JS...

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.

thrownaway561 5 years ago

All that sites does is make me glad I still use jQuery. If something is working and saves me time, I don't see the reason for me to have to replace it simply cause it is the next hot thing. jQuery has it's place in the world.

bisRepetita 5 years ago

One thing I need jQuery for: tracking progress on file upload. Fetch does not do it.

thecrumb 5 years ago

2021 ... still using jquery

murtazakhussain 5 years ago

wow, no other proof is needed to user jQuery :)

Keyboard Shortcuts

j
Next item
k
Previous item
o / Enter
Open selected item
?
Show this help
Esc
Close modal / clear selection