Hacker News new | past | comments | ask | show | jobs | submit login
Removing jQuery from GitHub.com frontend (twitter.com)
310 points by andyonthewings 7 months ago | hide | past | web | favorite | 250 comments



Removing jQuery is not always a good idea. The best advertisement for jQuery, ironically, is this site: http://youmightnotneedjquery.com/ Look at how simple things are in the left column, and how much more code is needed in the right column.

jQuery has many convenience features such as chaining, for example: item.addClass('selected').siblings().removeClass('selected'); and you don't have to check for nulls after each selection.

Many functions such as closest() and remove() have no equivalents in IE11, and other things such as replaceWith() and before() are not available even in Edge.

For simple sites it is easy enough to remove jQuery, but for more complex javascript applications, especially apps that have a lot of interactivity, removing jQuery will result in more code, or you will end up writing a lot of utility functions thereby creating your own little clone of jQuery.


I was one of the developers who made http://youmightnotneedjquery.com. To be fair, we made it in... 2014? There is a lot you can do now which you couldn't do then, just with a browser. A lot of the challenging examples, like animation, you're better off doing with straight CSS.

Ultimately, I haven't actually used jQuery for anything serious in half a decade, and somehow I manage.


> Ultimately, I haven't actually used jQuery for anything serious in half a decade, and somehow I manage.

I don't understand that sentiment ... Of course you can "manage" without JQuery. JQuery itself doesn't use JQuery (D'oh) and somehow it can do all these things, so it is possible. The point of JQuery is that I don't have to think about the various (slightly) incompatible implementations of <whatever> in each browser version, but can just use one lib call and be done with it.

JQuery to me is like using a car instead of running to another city. Yes, I could run, but why would I do that ..?


jQuery to me is like riding a bike with training wheels attached after you've been riding for ten years. You don't need them, but unless you try taking them off you'll never know that.

Browser incompatibilities are basically a non-issue these days for 95% of projects. Animations etc are far better done with CSS than jQuery (particularly when it comes to hardware acceleration). The Fetch API works in every browser. So on and so forth.

I think the OP wasn't suggesting that "managing" without jQuery is difficult. Certainly, I can say that I haven't touched jQuery in years and haven't looked back once. There's nothing I miss.


> jQuery to me is like riding a bike with training wheels attached after you've been riding for ten years. You don't need them, but unless you try taking them off you'll never know that.

Why even use wheels when you can reinvent them? I'm not saying there are no reasons to go "bare metal", but satisfying your developer ego is not one of them. Unless you need every inch of performance or control, jQuery (or alternatives) is probably the more reasonable choice.


Why would it be the reasonable choice when it was created to solve a problem that largely doesn't exist any more?

jQuery wouldn't be created today in anything like its current form. It still lives on largely because of inertia. Using the APIs provided by the browser is in no way reinventing the wheel!


There is now a whole generation of FE developers for whom "JavaScript" is synonymous with "JQuery", as evidenced by endless questions on StackOverflow which use the terms interchangeable.


I agree with this sentiment wholeheartedly.

A lot of the commenters here have a very old school view of jQuery. They seem to believe that if you're using jQuery, then you must also be employing manual DOM manipulations, manual state management, etc.

You can implement modern component-ized front-end architecture while still using jQuery. My company built an in-house front-end framework heavily inspired by React and Vue. But instead of abstracting away from the DOM, we've embraced the DOM by utilizing DocumentFragments for highly performant rendering. When our components render, they return regular ole HTMLElements.

The components built using our framework work with or without jQuery. No manual DOM manipulations, one-way data binding, sane state management, templating, child components, state triggers, etc. A lot of us use jQuery simply because we prefer it's compact and expressive syntax.


Because the wheels are proprietary and full of quirks. For instance, $('.foo') returns an array of jquery objects and not HTMLElements that you can act directly upon using the standard API that was made for replacing it.


>The Fetch API works in every browser

As long as you're using recent versions. The whole point of jQuery is that you can write some code and be sure that it will run correctly in older versions of the browsers.


That's not the whole point of jQuery, it's just one advantage.


Well XMLHttpRequest has support going back to IE7.


> The Fetch API works in every browser.

No it doesn't.


> The point of JQuery is that I don't have to think about the various (slightly) incompatible implementations

Sure when jQuery was released in 2006, but browsers have had 12 years to improve their compatibility, and they have. Javascript has also had 12 years to improve and simplify its api, and it has.

Your analogy was perfect for jQuery 2006 but in 2018 its more like buying a car to drive around the city or you can just take an Uber, you don't have to walk anymore.


Tell that to those enterprise customers holding to IE 11, not allowing Chrome and doing their own timely releases of FF ESR.


Where I work we only just upgraded to IE11 - it was a decent-sized project, involving a lot of people and manhours.

I really wish we'd of just ditched it and moved to Chrome or Firefox :(


So you would have a decent sized project involving lots of people and manhours, but without support from your vendor?


If someone is developing web applications in such a way that they need support from their browser vendor to make them work properly ... they're doing it wrong.


I was assuming that the upgrade was more of an IT thing, that all the company computers are now on IE11.


Yes, that's correct.

We have a portfolio of hundreds of applications, and needed to make sure every one worked OK on IE 11 before upgrading from IE 9.


Also don't forget mobile browsers. I ran into a strange problem where Samsung's "Internet" didn't support something and could not find any online mention of this fact.

(I wish I could remember what it was. Perhaps an array method).


Haha, I remember when that site was released, and a few of our developers jumped right on it without actually reading the text - namely the second paragraph.

> If you're developing a library on the other hand, please take a moment to consider if you actually need jQuery as a dependency. Maybe you can include a few lines of utility code, and forgo the requirement. If you're only targeting more modern browsers, you might not need anything more than what the browser ships with.

Back then, you were 100% correct that if you were writing a library that you intend to use in other places, having jQuery as a hard requirement was a bad idea. However, one developer managed to convince their PM's to completely strip out jQuery for an upcoming project, despite the fact that this website was for a major charity that had huge accessibility requirements AND required legacy browser support. The devs on that project learned a ton about vanilla JS, but that project was an absolute disaster.

We did get a solid library out of it, though, and at least that didn't have jQuery as a dependency!


That's more telling about problematic mechanics in your org than about jQuery itself.

Did that convincing developer have more influence than the rest of the team? Why the PM was involved in implementation minutiae?

From what I've seen people tend to complain about office politics usually when they don't grok them. The not grokking part is often a choice stemming from a conviction that code monkeys > managers because "engineering". Following your example, who then has more influence over technical decisions? (at least in your somewhat disfunctional org?)


I think you're reading into it a bit too heavily.

At that company (small agency), at that particular time, the structure was flat, and this was isolated to a project he was leading. It was raised in a developer meeting, where I said the point was that libraries shouldn't have hard dependencies, not that (in 2014) we should be ditching jQuery and writing vanilla JS, especially on projects that needed legacy browser support. He ignored me, and the project ran over by months and causing the company to make a loss.

Company issues aside, he wasn't the only developer to not RTFM at the time, and the site was shared across the web by people calling for the death of jQuery when it still had a very legitimate use.


It is a little irritating when libraries that really shouldn't need jQuery had it as a dep. I don't mind using jQuery, but I'd rather not add it to a project just as a dep.


Absolutely. In the case of libraries it was absolutely solid advice.

Sadly, a lot of people didn't actually read the site, and they decided that jQuery was evil and shouldn't be used on websites at all.


It is not about the possibility. We can achieve anything with native browser's APIs without custom/polyfill layers these days.

Point is:

$('#somediv').removeClass('class-to-be-removed')

is so much better than

document.querySelector("#somediv").className = document.querySelector("#somediv").className.replace(/\class-to-be-removed\b/,'');


Broadly speaking I agree with you, but even IE11 supports classList so the "native" version of your bit is really

    document.getElementById('somediv').classList.remove('class-to-be-removed')
Where the native APIs fall down is that

1. they tend not to be chainable/expression-oriented, you can't just `classList.add('foo').remove('bar').toggle('qux')` because the first two methods return `undefined` and the last one a boolean

2. they don't support set-oriented operations at all, it's a chore of manual iterations


Spot on! Those are probably the two most important blunt-sides of native APIs.

The last thing I'd want to see is a codebase going from 40 lines of code to 400 lines, because "hey, we removed jQuery and writing verbose js is the new cool these days"

I'd be happy if there's a jquery like polyfill library for DOM manipulation, but again - why not just custom jQuery builds and sizzle.js instead of re-inventing jQuery?

P.S I'm not sure IE11 supports classList. Source: https://developer.mozilla.org/en-US/docs/Web/API/Element/cla...


> P.S I'm not sure IE11 supports classList. Source: https://developer.mozilla.org/en-US/docs/Web/API/Element/cla....

It provides basic support for classlist, add/remove/toggle exist and work as you'd expect. It does not have complete supports of all bits of the API:

* it doesn't support the second argument to toggle so you have to use a conditional/ternary with add/remove

* it doesn't support passing multiple classes to add/remove

* it doesn't support replace


IE11 supports classList just fine, except for an argument to toggle. Nothing a little DOMTokenList.prototype change can't fix.

> The last thing I'd want to see is a codebase going from 40 lines of code to 400 lines, because "hey, we removed jQuery and writing verbose js is the new cool these days"

That will only happen if you're incompetent and will not write a few simple helper functions. And probably not even then. Plain DOM API is not that verbose over jQuery. Anyway, just look at what subset of jQuery you use the most and write helpers for that.

Your codebase is already grown by 1000s of lines by using jQuery, so you have quite a head start sizewise if you drop jQuery.


Another tweet says that removing chaining improved readability...

https://twitter.com/mislav/status/1022409388013834240

But this I'd say is very close to BS territory..


It was me, who asked him the question. The answer though isn't satisfactory enough. But again 140 chars is not a good bandwidth for meaningful conversations.

The claim is interesting, but isn't evident enough.

For example, how exactly is

    var element = document.querySelectorAll('.container') 
    element.style.paddingTop = "50px"; 
    element.className = element.className + 'header';
communicating intent better than:

    $('.container').css('padding-top','50').addClass('header')


While I do agree in your comparison the second version looks better. At the same time, and this might be a tad too subjective to have much merit, it feels out of place to me.

Instead, I'd use one of the various approaches where I can create a style = {} object and then apply it to the element, which would just fit better within the rest of my javascript.

(which particular approach to use, .cssText, looping through props, or Object.assign, I'm not sure, but my point is any approach that applies a POJO to the node instead of chaining strikes me as more idiomatic. this is not a hill I'd die on though...)


I wonder how many people will notice that your non-jQuery example actually contains a subtle bug.


Re 2.:

el.querySelectorAll('abc').map(el => ...)...

You may need to copy some methods you'd like to use from Array.prototype to NodeList.prototype though, or use .values() from NodeList everywhere.


That's manual iteration even if it's done via HoF.

Many of jQuery's operations implicitly apply to the entire nodeset regardless of the nodeset's arity.


Fair point, though for dynamic and large DOMs I dislike having to go and check whether I’m touching more than one element sometimes — not always though, sometimes it great to just $(‘#bleh’).hide() or what have you! Depends really


That's completely fair, and there are cases where unknowingly selecting and applying complex operations to many nodes is problematic but I think it's a great baseline/default regardless.


I usually add: const qs = (selector) => [...document.querySelectorAll(selector)]

so that I can tread my results as a normal array.



[Same Link] You can see how poor the browser support is and how big the polyfill is. There's a chance that the polyfill could be bigger than jQuery's removeClass/addClass implementations.


FWIW, a few of the non-jQuery alternatives documented on http://youmightnotneedjquery.com are not equivalent -- they lack some of the functionality that jQuery offers. For example, take a look at $.replaceWith(). If you use $.replaceWith() you can supply an element that has event handlers bound to it and those event handlers will persist after the replacement. But in your alternative code ( el.outerHTML = string; ) you can only pass in a string which of course cannot have event handlers bound to it.


Is it time to make that site open source and update it, then? Maybe make a version that targets IE 11+ or even discards Edge, that way you can show promises / async/await for just the ajax one, as well as the straight CSS solutions.


It is open source. Repo: https://github.com/HubSpot/YouMightNotNeedjQuery

License is MIT.

Unfortunately it seems to be unmaintained.


I kind of imagine we will one day have a basic poly fill for all the cross platform issues jQuery actually excels at, and then we truly won’t need jQuery since that’s all it’s really good at these days. Things like chaining are an anti pattern and lead to brittle code!


Oh, but we already do have that, over there: https://jquery.com/

What's with the trend "jQ is old, old is bad! We need something that does the same thing, and most importantly is not named jQuery"?


Most DOM manipulation in jQuery goes through jQuery.globalEval, which uses eval(). Meaning if you want to have a CSP, you have to allow unsafe-eval if you need to support jQuery.

CSP is an incredibly useful tool, and it’s close to impossible to use it properly with jQuery.


First concrete, legitimate reason I've seen all thread. Is there something fundamental about jQuery's design that forces it to use eval(), or is it possible a new version could avoids that?


Performing evals is a core part of the design. Take a look at the additional notes section on this documentation of the .html method.

http://api.jquery.com/html/

>By design, any jQuery constructor or method that accepts an HTML string — jQuery(), .append(), .after(), etc. — can potentially execute code

This makes jQuery less safe in general, but I think the CSP restrictions this puts in place are probably a greater issue for most people. I’ve been involved in retro-fitting strict CSPs into a few projects, and more than once I’ve been thwarted by very minor use of jQuery in a couple of places.


It's part of the design of the creation of new elements. But that's just one part of jQuery, and a part I would be completely okay with jQuery getting rid of.


I don't think I can agree with that idea about chaining.


I think those are some broad generalizations that I can't agree with, but Sizzle might be what you're looking for.

https://github.com/jquery/sizzle/wiki


Sizzle is ancient history at this point. It's the selector engine jQuery used before querySelector became available everywhere.


Yes, that was the point. What did you think I thought Sizzle was?


"might be what you're looking for", when that person was looking for a "basic poly fill for all the cross platform issues jQuery actually excels at"


Exactly rice. A possible answer to a somewhat ambiguous desire.


It would be cool if that website was updated then.


If you only care about writing code, sure.

But in this case (as in many others), code is written just a couple of times per month, and executed millions of times per day in millions of computers all around the world.

Therefore this kind of "low level JavaScript"* optimizations will have a net benefit much, much bigger than the convenience of reading shorter code for a relatively small group of people.

* Quite the contradiction, I know.


Each computer executes it a limited number of times, with lightning speed. Differences are imperceptible. The cumulative effect you are speaking of is hypothetical.

Writing code which just works on multiple browsers results in faster development and easier to maintain code and frees dev cycles to focus on performance.


> frees dev cycles to focus on performance

Perhaps this is the case--jQuery saved them so much time that they've reached a point where they are free to optimize their frontend by removing jQuery.


Maybe these are not the same developers?

I know I may be replacing jquery with stimulus or eventually vuejs but writing 5 lines of jquery code for my MVP is exactly the right balance today.


Knuth would approve. If you don't have a product, what are you optimizing?


> Differences are imperceptible.

That argument sounds very postmodern. The main issue with perception is that it easily tricked and even more, it can be strongly influenced by bias.

The cumulative effect can surely be measured and reasoned about.

It is very different to program for your new startup idea where adding features faster than your competition is more important than anything else in order to grow your user base, compared to improving an established product already being used by millions of people.

Different needs, different approaches.


> The main issue with perception is that it easily tricked and even more, it can be strongly influenced by bias.

I agree that this is an issue, mainly with all kinds of manipulation in politics and product quality/quantity/health impacts but the 5ms vs 2ms execution time of JavaScript is not one of the problems.

I’d focus on humanity gleefully steering itself into a climate collapse and mass ecocide while focusing on all kinds of completely irrelevant bs.


Things have changed since then. For example, AJAX now is much simpler to use than it used to be.

    async function printExampleCom() {
        let response = await fetch("https://www.example.com/")
        // NB: Response has other methods like json.
        console.log(await response.text())
    }
    printExampleCom()
You need a polyfill for `Request` for Safari and Internet Explorer (but not Edge), but that's about it.


Yeah actually I stead of so much focus on frameworks it's better to focus on better polyfill implementations. It's only a temporary issue in many cases but the larger web does move slowly and then stardards like web components sometimes take a deacde or more to be fully baked. Wasm based polyfill would enable more browser maker innovation and competition without leading to slow and bloared pages for all but one device.


What's the point of polyfilling a nice API when you could just have a nice API to start with which leverages native functions when present? They don't seem to be philosophically different.

Or stated differently, "jQuery is just a JS polyfill for browsers that don't support native jQuery yet."


Is there really much of a philosophical difference between a polyfill that exposes a common API and emulates when not present and a library that exposes a common API and uses native functionality when present?


If you have even medium complexity you're better off using something like React with Babel or Typescript. Much more sane way of event handling than JQuery, and no mucking with HTML by hand.

I agree with JQuery for the most simple sites, but React+transpiler will give you much better compatibility


It sounds like you're saying using jQuery and a modern component-ized front-end framework are mutually exclusive. jQuery and modern front-end components can go together very easily -- albeit not specifically with React and Vue.

Our company built an in-house front-end framework heavily inspired by React and Vue. The components built using the framework work with or without jQuery. No manual DOM manipulations, one-way data binding, sane state management, templating, etc. Many of us prefer to use jQuery because of how compact and expressive the syntax is.

It really surprises me how many people think that jQuery === old school manual DOM manipulations. It definitely doesn't have to be that way.


Thing is react is only compatible with react ;-)


It's extremely easy to use React in small parts of the page and spread it out over time. It's a couple lines of code to init React in a div and fully supported. You can even communicate between React bits spread across the page.

React also let's you mark areas/divs within its domain as "don't touch this". So in those areas you can use things like that old map widget you love so much, without resorting to iframes

Angular is a huge fail in this regard. Zero support for mixing with "non angular" pages.


All what you describe in this commentary is much more easy to implement with just jQuery. Your logic more looks like "I can do it with React so it means I should and I believe it's the best tool".


Until you’ve got some moderately complex state and infrastructure to handle it, where you end up recreating the whole State -> Render loop of React in jQuery. I recently did this. It works, well, and with less bugs than most hacky jQuery DOM modification, but by the end I was pining for any other modern view library that already solved this. Same reason I used to pine for jQuery on some projects.


Can you elaborate on this? In my limited experience with React, it takes over your whole application, or at least the whole page. How do you mark areas as "don't touch this"?


I'm not sure on the "don't touch this" part, but in regards to "taking over the application", it certainly doesn't.

React's entry point is the `ReactDOM.render` function, which takes some React elements, and a root node. that root node can be _any_ DOM node (Actually no idea if you can mount React into a inline SVG, but at least any _HTML_ node you certainly can). You can also have multiple `ReactDOM.render` calls, no problem at all.

That initial React element can very well take values and callbacks from your Angular or whatever application.

It can get messy if you nest `ReactDOM.render` within roots that are managed by React, but so would nesting any other UI framework, but the use cases for that are... Exuberantly exotic, to say the least.


So, the way to look at it is that you “mount” a React application at a specific part of the DOM. Anything under that point is managed by React components.

Usually, people have a single “mount point” very close to the <body> element, and a single script file whose primary purpose is to call ReactDOM.render to “mount” a React component representing their application at that point.

However, that doesn’t prevent you from having DOM outside that mount point, and it doesn’t prevent you from having code which does other things that don’t have anything to do with the React-managed part of the page. This is a great way to migrate a legacy application to React: you choose one small section of your page to replace with React, and then have the remainder of your page interact with it by 1.) choosing when to call ReactDOM.render again to ask it to update, and 2.) passing in callbacks so the React ”mini-app” can notify the rest of your application when something happens.

You can go the other way, too, although it’s a little less safe. If you have a React component which renders, say, a <div> with no children, you can get a handle to the DOM element itself and interact with it just like you would in a non-React application. The only constraint here is that you have to make sure to clean up e.g. event handlers and release references to those elements if something causes the “owner” React component to unmount. This is how people make wrapper libraries which let you use non-React-based libraries using React components. (I’ve done this in a side project where I had a huge number homogenous DOM elements to work with, and found that managing them myself was much more performant than trying to run them through React’s model.)


i have something like that in one of my projects, there is "inbox" in one of my apps, it is handled with react, and the header, and top menu are outside of react and generated from backend. it works great. the only problem i had is in the developing, the thing that i did is i developed the inbox feature separately and then im copying the dist to my app on compile.


I haven't had to do so much myself, but the docs have decent info on how to obtain it. https://reactjs.org/docs/integrating-with-other-libraries.ht...


React components mount to any element you want. And everything they do will happen within that element if you are using react conventionally. There is no issue mounting components alongside/inside legacy apps.


Angular is a nightmare for complex UI interactions for components that are spread out.

I'm sure experienced people know how to do that properly, but it's really difficult starting out.


Angular's learning curve is the worst I've ever seen. We mostly use it because "Enterprise" but I prefer React when we get permission for that reason.

Too much abstraction, too much magic. It's possible to do just about anything but the docs are sparse enough that you'll be crawling through github PR's and source to figure out how to achieve it sometimes


Angular is an amazing tool for building reusable components and interoperation between them is pretty easy to implement (just use "input/output" handlers). I'm not saying it just to say something opposite, it is really my opinion and it's what I do almost every day.


Can you elaborate on this? I've integrated React into Angular and Ember projects in the past with no compatibility issues.


Did the "foreign" elements stamp out react elements or interact with their properties?


I tried not to have multiple frameworks controlling the same DOM elements. It would usually be a React component mounted to a DOM element controlled by a component in another framework.


Exactly, that is my problem, if a react component state is altered by "outside world", weird things can happen. So you actually avoided interoperability between solutions.


why not Vue?


"something like React" includes Vue.


React is great for rendering (and updating after initial render), but if your app is highly interactive then jQuery makes things easier even when using React for rendering.


You generally don't mix react and JQuery. The event system + JSX makes jQuery obsolete.

Having worked in complex interactive React/Angular apps as well as ones using JQuery, nobody would ever offer me enough to use JQuery again for this use case. They would have to double my pay for all the pain


Show me a dropdown menu written in React and I'll show you how you can simplify the code significantly by using jQuery in addition to React.


Development with React is becoming similar to old school event driven desktop apps, thankfully.

If I want a fancy drop-down with accessibility support and theming etc, there's probably 50 different libraries with components I can pull in and use with little fuss. A few lines of code to import and register event listeners.

I was a huge user of jQuery for years, and it also has quite nice UI libraries. But the power of React is the standardized scaffold and lifecycle. I can pull in UI components from almost any library and use them intuitively. Mix and match them on the same page.

Trying to do that in jQuery will quickly drag you to hell.


>Trying to do that in jQuery will quickly drag you to hell.

Can you elaborate on this please ? I've used lots of libraries with jquery and haven't encountered problems.


Easy to cause it by combining bootstrap components and JQueryUI.

In React you can "scope" a components CSS so none of the styling leaks out


Can you be more concrete?

If you want some specific code to criticise, there's dozens of dropdown menu widgets available: here's one I found in Google https://github.com/react-component/menu since I've never actually had reason to use a js/html drop down menu widget.


Here's one that uses jQuery. See how much simpler it is? The one you found does have more functionality, but try rewriting the one I found in React without using jQuery. I guarantee it will be much more complicated.

https://github.com/wisercoder/uibuilder/blob/master/SimpleDe...


It’s interesting that you find this “simpler”. One of the great advantages of React is that is declarative, it’s easy to understand how a component will render given a set of (props, state). Your example is quite the opposite, the render method violates this principle and each event handler manipulates the DOM using a ref. I’d call this spaghetti-React.


Did you miss the fact that this component is interactive? You can't do interactivity declaratively.


By declaratively I mean that in React you typically declare how an element should be render given the current (props, [state]).

For example, in vanilla JS, you might have something like:

  const btn = document.createElement('button');
  btn.className = 'btn red';
  btn.onclick = function(event) {
   if (this.classList.contains('red')) {
     this.classList.remove('red');
     this.classList.add('blue');
   } else {
     this.classList.remove('blue');
     this.classList.add('red');
   }
  };

In React instead:

  class Button extends React.Component {
    state = { color: 'red' }
    handleChange = () => {
      const color = this.state.color === 'red' ? 'blue' : 'red';
      this.setState({ color });
    }
    render() {
      return (<div>
        <button 
           className=`btn ${this.state.color}`
           onClick={this.handleChange}>
        </button>
      </div>);
    }
  }
I find it simpler to understand, because render, given its state, describes exactly how the UI should be.


This only works for simple cases. Where this breaks down is when you have to inspect the current state of the DOM before deciding what changes to make to it. Example: scroll an element into view if it is not already visible. More examples: drag & drop, interactive resize, etc.


It's not about how complex the component is. In my experience what matters is how easy it is to use. With React it's easy to build a world in a teacup, and that's mostly a good thing.

For "regular CRUD developers", the vast majority of us, I have zero concern about how big or crazy component code is until it's so huge it impacts page size. I'll use the easiest most feature complete library out there.

React does encapsulation like jQuery never could. I don't care if I have this vanta black box on my page as long as it's easy to mess with and gets the job done


"I have zero concern about how big or crazy component code is until it's so huge it impacts page size." Me and my mobile browser would like to have a few words with you. Not everything that can execute JS is a supercomputer...performance still matters.


You don't care if the code is significantly simpler by using jQuery? I do care. Simpler code is likely to have fewer bugs and is easier to maintain.


I'm talking about my code specifically. With React I can pull in a massively complex UI component in few lines.

The complexity is shifted to the library that hopefully has thousands of users so is mostly bug free. It simplifies my code at the expense of moving complexity to the shared project. Much preffered since my code will see orders of magnitude less usage than the library itself


I care debugibilty and maintainibility. Many projects on github have very short life cycle. If it go unmaintained, how easy can I take over it?


I would argue that most websites have a lifetime similar to the components :). For the ones that don't, backwards compatibility on the web is amazing, only thing to worry about is security vulns


You're correct that simpler code is better, but here's my argument: Large jQuery applications are not simpler, have more bugs, are harder to maintain and have poorer performance than React applications.

jQuery is a DOM manipulation utility library. React is a view rendering library, favoring composition and isolated components.


What do you even need javascript for in a dropdown?


How else are you going to add back in the accessibility you've broken by building it with JavaScript?


For filtering as you type?


you are seriously mistaken about react then. The whole point of MV libs is that you maintain a model (domain and/or UI) and the UI just redraws itself. JQuery is 100% not needed even for the most complicated React apps.


When you have a highly interactive component you're going to need to make a lot of DOM calls to get the current state of the elements and so on. jQuery makes this easy. The benefits of jQuery over making raw DOM calls have been mentioned by many people here already, so I won't repeat them. These benefits of jQuery don't go away even in a React app.


> Many functions such as closest() and remove() have no equivalents in IE11, and other things such as replaceWith() and before() are not available even in Edge.

Many of these can be polyfilled, Going the polyfill route IMHO is a bit better. I use this now : https://polyfill.io .


That polyfill relies on a third party which can then effectively gain analytics for your site. They store and keep the referring URLs and user agent combinations.


> That polyfill relies on a third party which can then effectively gain analytics for your site. They store and keep the referring URLs and user agent combinations.

That polyfill relies on nothing since you can run your own custom 'polyfill' server, or just download the bundle and serve it from your website. It's completely open source.

https://github.com/Financial-Times/polyfill-service

You're complaining that a public CDN runs some analytics. But they all do that, and this project doesn't mandate that you use their CDN.


> other things such as replaceWith() and before() are not available even in Edge

Huh? http://youmightnotneedjquery.com/#replace_from_html and http://youmightnotneedjquery.com/#before show solutions that work in IE8+ and Edge.


The replaceWith() function as documented here does not work in IE: https://developer.mozilla.org/en-US/docs/Web/API/ChildNode/r... You may be able to find hacky alternatives, but if you use jQuery you don't have to.


element.replaceWith(replacement) is just an alias for element.parentNode.replaceChild(element, replacement) with some bonus functionality to convert strings to DOM text nodes. parentNode.replaceChild is not exactly a 'hacky' alternative.

Here it is in the form of a basic polyfill that only supports Elements:

    Element.prototype.replaceWith = function(replacement) {
        if (typeof replacement === "string") {
            replacement = this.ownerDocument.createTextNode(replacement);
        }
        this.parentNode.replaceChild(this, replacement);
    }


Is that just as readable? Is the intent just as clear? Is the improved readability of the jQuery version worth the extra 80kb download to you?

EDIT: Regarding the polyfill, now you are beginning to write your own little jQuery clone.


GitHub says they are using polyfills instead of jQuery as well. The point is to not have to rely on external frameworks.


> The point is to not have to rely on external frameworks.

Why is that a worthwhile goal?


To reduce attack surface as well as maintenance burden for compatibility whenever something breaks during an upgrade.

A polyfill is something that's not needed at all in modern browsers and thus can be considered pretty much final. jQuery is actually surprisingly stable compared to Angular/React/npm/rest-of-the-hipster-crap, but it has had its fair share of incompatibilities too.


Is a set of polyfills philosophically different than a framework?


To be fair, that site doesn't use `fetch` on the ES side which bloats all the starting examples.

Further, there are many better animation libraries.

And finally if you use any view framework you have very little need to be traversing the DOM.


For comparison, here's the first example, but using fetch:

    fetch('/my/url').then((r) => r.json()).then((data) => {

    })
And as an added bonus, fetch uses promises, so in an async function that's just:

    let data = await fetch('/my/url').then((r) => r.json())


I'm not a fan of mixing await and .then myself;

    let data = await (await fetch('/my/url')).json();
That's a one-liner, but you can split the request and json data as well (and you usually want to anyway because of error handling).


You can write `(r)` like this `r`. Remove clutter. You don't write `let i = (0)`


That’s not a good analogy at all, the () is there in arrow functions always except, as a special case, it’s optional if there’s a single argument.


There's also the native Web Animations API!


Yeah, it doesn't serve the site well to include the animation and XHR stuff right at the top.

But if you had a small site that just needed to perform a few DOM manipulations, this would be highly relevant. If I just need to pop a div open and closed when a button is clicked, I sure won't bring in jquery just for that.


The reason I used jQuery is to have script working on every browser in the wild. Now that jQuery dropped support for old browsers, this advantage is no more (sure, I could use old jQuery, actually I'm doing exactly it, but I don't like to use outdated versions). I think that it was one of strongest point of jQuery and the that they decided to get rid of it is questionable decision.


It sounds like someone (motivated enough) should fork jQuery before the old browsers support got removed and maintain it as jQuery-legacy, backporting fixes from "new" jQuery" if applicable.


That's one paradigm that operates directly on the DOM, but, a lot of modern-day development tools (e.g. redux) don't work like that, and their programming model is a lot more straightforward than "remove the selected property from all siblings", instead just having a selected boolean expression for each element.

The performance question becomes a bit more tricky too then, because instead of comparing direct DOM manipulation you're comparing 'rendering' as a more abstract concept.


While we're on the topic of our favorite JS toolsets, I've been having a blast using just a ES6 transpiler and Greensock. No need for neither jQuery nor a giant SPA framework.


I don't think there's a good replacement for:

$(document).on("click", "#foo", function(){...});

either


Event delegation was a thing before jQuery, and is not that hard to implement as a helper function, e.g.

https://jsfiddle.net/jbctqupz/



Indeed its easy! But damn it gets boring having everyone patch the DOM with things that should be in the standard DOM API already by now.


Is that not simply

    document.getElementById('foo').addEventListener('click', function() { ... });

?


The vanilla equivalent of:

  $(document).on("click", "#foo", function(){...});
is:

  document.addEventListener('click', function (ev) {
    if (ev.target.matches('#foo')) {
    
    }
  });
The advantage is that #foo can come and go (after page load be injected and removed and injected again, but the event listener must be registered just once.

Since the example is an ID (#foo) the advantage is less obvious. Something like a class (.foo) makes it clearer that there could be many, and it could get expensive to attach an event handler to each one --- though I'm guessing it takes hundreds before it becomes a big deal. But again, .foo's can come and go without having to worry about reattaching the event handler.

P. S. My library, https://github.com/combatentropy/listenup.js (31 lines)


Well, it could be. As long as #foo exists on the page at the time that line is executed. If you inject #foo into the page after load then the click event won't work.

The jquery example delegates #foo, so it can be injected in the page after load and the click event will still work.

But there are ways to mimic the behavior as another person has pointed out.


It does get much closer when you set the minim IE version to 10.


Maybe the percentage of people browsin github on IE11 is 0%?


It's rather ironic how in object-oriented programming chaining is considered a bad practice, e.g., breaking the Law of Demeter.


> breaking the Law of Demeter

How so?

You have an instance. You're allowed to call methods or access properties of that instance. You're not supposed to call methods or access properties of properties.

So chaining is just:

    $foo.something().somethingelse().blah();
At each point you're getting a new instance and accessing that. You're never reaching inside of a property of that instance.


If GP is correct re failure propagation then this is monadic composition vs. OOP object chaining.


Bloat and slowdown for the customer is not worth the dev convenience and no library can fix poor work organisation.


It isn't about writing code. As a developer writing code is your job. If writing a couple of extra lines of code makes you sad then perhaps this isn't your cup of tea.

For me it has always been about performance. jQuery is slow. Even way back in the day before JavaScript got fast you could access the DOM quickly if you knew what you were doing. Likewise DOM access could easily make your code 5 times slower if you didn't know what you were doing.

Since 2012 JavaScript has been fast in every major browser and querySelectors are a standard feature. Since about that time accessing the DOM has always been 10s-100s of times faster than using the standard querySelectors. In Firefox it is 10s of thousands of times faster. The standard querySelectors are faster than using modern jQuery.

To me this is the difference between a junior developer and a competent developer. Some people NEED the extra help. I understand that. If product quality and achieving a superior user experience are important though you will simply figure out a better way of writing code, especially since writing code is probably your job.


Software development is a lot about making good use of resources and if you reinvent the wheel for every job you do, maybe it isn't your cup of tea.

I've worked with developers who completely ignored good libraries and instead created their own terrible implementations. They got nothing done and what they did was a buggy mess that often needed months of patching.

Finding a good middle ground is the best way to go and when the loading time increases by only a few milliseconds, but the development is a lot faster and cheaper, that's a good compromise in most cases.


Cliche ad nausium. It’s like saying I should never have to write my name more than once, because it is reinventing the wheel.

In this case every call to the DOM goes from a slow baby crawl to rocket speed. In no other aspect of life do people make such empty excuses, using cliches no less, to intentionally remain in the stone age.


Well, considering there are devices out there for the purpose of signing names repeatedly, I would say your example doesn't necessarily work.

Totally depends on the situation.

And why the assumption that modern versions of jQuery don't make use of modern DOM APIs?


Here is what makes jQuery slow, both now and in the past:

* querySelectors (standard or the home grown Sizzle engine)

* Method chaining for trivial tasks, in many cases to compute data that is already statically present or directly assignable.

Regardless of whether jQuery is using modern APIs or not there are old standards available, to JavaScript, that just about everything in jQuery eventually compiles down to. At the end of the day it becomes a matter of whether writing a couple of 3 line abstractions is far too hard of work or whether it is simply easier to push everything through 65k of jQuery purely for the sake of familiarity.


"friend to your coworkers, enemy to your craft"


I'm impressed. I don't think the web would be where it is today without JQuery, and being able to completely pull it out is pretty awesome. Not because of JQ-hate, but web standards have improved that much.


I think it's a testament to jQuery's influence that, even though many of us don't use it today, we still often think in a jQuery way. The most useful common bits of jQuery's approach got baked into standards.

I think it's impressive that even when I'm not using jQuery (haven't in many years), I find myself writing code using features/capabilities where jQuery was an obvious inspiration.


I mean, when you think about how many people were using jQuery for

(a) cross-browser compatibility, which mostly works now (except for cutting edge stuff, which is pretty optional) (b) $.ajax (uses that could be replaced by window.fetch) (c) Sizzle (Replaced by document.querySelector[All])


Yeah. And IIRC, all of this came about as "let's take these awesome pieces of jQuery (which were written because browsers sucked) and reimplement them natively." Now the roles are apparently reversed, with jQuery being the Big Bad?


(d) the plugin system, which is replaced by Custom Elements (but unfortunately the React crowd is there with their own custom private component system)


Very much this. There are very few scenarios in which I’d recommend jQuery nowadays, but I still have mad respect for the project itself, for its legacy, and for the positive impact it’s had on front-end programming.


Yeah think of how many Javascript questions on Stackoverflow have jQuery answers


jQuery was awesome, and needs to be entered into some kind of web-tech historical hall of fame. But it's time has come to be replaced.

I had used Prototype.js, and just a couple years ago finally gutted it from our code base. And shortly after started removing jQuery. It's a long slow process.

After starting with Vue.js, I completely understand why jQuery is no longer needed. Vanilla JS/CSS3 does 98% of what jQuery did for us, and our own micro-library fills in the blanks. And Vue is replacing all the jQuery scaffolded apps.

If it weren't for reactive interface libraries though, jQuery would still be a staple.

One example, I use a jQuery library for sorting tables. When I saw how sorting a table is so basically easy in Vue.js, that no plugins or 3rd party code needed, I saw the downfall of jQuery in general.


I don't understand what you're talking about. Jquery is still a highly effective library and nearly every project I use ends up using it in one way or another - even with vue.js.

Jquery is JUST jquery. There is no pulling in 300 other packages to support it. It's also very stable, reliable, efficient enjoyable.

this is how you might sort a table using a Jquery library:

$("#myTable").tablesorter()

And here's how to do it in Vue (first search result for vue table sort):

https://www.raymondcamden.com/2018/02/08/building-table-sort...

You'll note that it is a lot more code to sort with Vue than with a jquery library.

Don't get me wrong; I like Vue; But Jquery offers one line of code that enhances the existing HTML you have, where doing it with Vue.js requires delegating the entire table render to Vue, which may not be easy or even doable depending on the project.

I think things like Vue.js or stimulus.js let Jquery do more with what it's good at and less of what it's not. I'm very happy to have Jquery in my toolbox and I doubt I'll ever stop using it at this point. You're welcome to hate on it, call it dated or what have you - i still love it and it's still the best tool for quite a lot of jobs.


That line looks like complete gibberish to me. If my task is to fix a bug in the sorted table, I expect to find a list of somekind (the data source) and a (set of) sorting functions that can sort the data set. Not a magical #id ref and mysterious method call.


Well, you’re delegating the entire rendering to jQuery and hiding all of the manual work in a dependency. The lines of code are still there, you just didn’t write them yourself.

It’s not a fair comparison.


What? no you're not. You're augmenting existing, already rendered HTML with Jquery. have you never used Jquery before?


I just ran into this quote somewhere (I am rewording cause I can't find it)

"It's like eye glasses, you'll know when you need them" - Some smart guy

I needed something jQuery could not provide, easing my work load.

Let's look at this from 2 different perspectives:

1. You're building an app, and work with multiple tables to render and work with. And you have integrated form elements with the table cells that affect other cells. You need to add/remove items using AJAX data calls to the server and sync the display with the server data. And you fully expect to be making more changes in the future.

2. You have a table on a website(s) as content you want sorted.

I've used jQuery to do both, but with Vue.js I cut my code base down by 1/10th at least, and it works smoother and easier and way easier to extend and add new features.

I have used jQuery exclusively for all my front end work, but I have an app that just kept needing more and more features. And every time I had to add a feature I went through so many hoops and patching stuff and dealing with edge case uses, and _hoping_ the jQuery plugins I was using had my back when I upgraded jQuery, or when I needed just a slight tweak on how a table was to be manipulated.

With Vue.js, adding sorting to a table was literally 5-10 lines of code, that I have total control over. This is possible because I don't have to deal with the html directly.

I was a die-hard jQuery man just last month, if you have the time, read my other comments, I defended it to death. And yes, it still likely has it's uses, but in my experience (full stack dev for almost 20 years) I can do everything jQuery can, and often times better, on my own now. jQuery can "simplify" some code, but that doesn't make the code easier to work with or extend, it just makes it "shorter", which isn't much value anymore to me.

Regarding this example: https://www.raymondcamden.com/2018/02/08/building-table-sort...

That's not extra work because I replaced my server side render of the table (which had a library for rendering tables) to doing it entirely on the front end. I just get to pass it data. (yay!)

Also the jQuery plugin I use is hugely bloated, and I only need a fraction of the features.

I have thousands of lines of code using jQuery still active in my code base. I just started with Vue.js last week, and I only tried it because I was so daunted by my tasks ahead to build a version 3 of an app. Within a couple of hours of development everything got easier.

If you don't experience this when using Vue.js (or other reactive library), then jQuery is obviously perfect for you.

--

Edit: This is the jQuery table sorting plugin I used, because I needed heavy duty features.

https://github.com/Mottie/tablesorter

In total, 240k MINIMIZED code plus css, images, etc... The file size alone is incredible. When I am done making a proper component with Vue.js to do the work I use this for, I bet it will be 10k or less easily, and that will include the html scaffolding and rendering to boot.

For a blog post jQuery is just fine. For a fully supported long term app that produces income? Vue.js all the way, even for something as simple as sorting a table.

--

Edit: Consider if you want to change from a table to divs with grid? Or list? You can't with jQuery because you only have a table sorting plugin. All it's classes and rendering are for tables.

https://jsfiddle.net/rg50h7hx/788/

Look how little code it takes to sort the data in that example. This was just crazy to me when I first ran into this.

Here's the actual example I ran into that opened my eyes to the simplicity of using data to render the html through Vue.js

http://www.developerdrive.com/2017/07/creating-a-data-table-...

57 lines of js code for sorting, pagination AND data for the table!


I don't even bother with vanilla JS. Babel and Typescript let you magically use the latest features without caring about compatibility at all really, except CSS


People often promote this but there’s a huge gap between script tag to include jquerg.min (for example) and requiring the entire node/npm ecosystem to cross compile etc everything else (provided you weren’t already). This is a high tax to pay.


Typescript is super easy to bring into a project. Just rename .js to .ts and turn the validations off. Any valid JS is also valid TS. Build step is one command to run tsc. You can turn things on slowly as you refactor into idiomatic typescript.

React is a PITA to setup and learn, as is Angular. They're the modern equivalent of Java EE. "Heavy" but if you have something complex to do and know your way around they make hard things easy. The learning curve is tough but so worth it


How are these ("vanilla JS" and "the latest features") different things? By vanilla JS, do you mean prior to 2015 JS?


Transpiled JS specifically. JS is the only popular language with a great deal of differences between versions and runtimes, mostly due to rapid improvements. If you use "vanilla" ES2017 without transpilation you're in for a deluge of bug reports.

Instead of worrying about browser Y supporting feature X, I just ram everything through Babel or Typescript compilers and use all the newest features.

We haven't had a single browser specific JS bug since we started using Typescript on ny project last year. And async is so damn nice.

Babel's output is a bit obtuse sometimes, but Typescript was designed to output idiomatic JS, so even with no sourcemaps code is perfectly readable before minification


How big is the compiled output?


In my experience (compiling TS + babel down to ES5), the compiled output is generally fine. Unless you're trying to squeeze every last kb out of it, asset optimization and NPM dependency bloat are much bigger optimization opportunities anyway.


Haven't looked at Babel's, but the output from Typescript is human readable and not much bigger than the original. The more polyfills (lower your target lib aka ES3 vs ES2015) The bigger the output.

Even targeting the oldest crappiest browsers doesn't add that much. Some maybe 50kb for polyfills injected and code bloat of 30% ish. Not much price to pay to use the latest features without caring about compatibility


i offer wonder where the state of the web would be if John Resig never would have created jquery. i think everyone who is into web development today owes a thank you to him. jquery single-handedly made programming on the browser easier.


> jquery single-handedly made programming on the browser easier.

Besides jQuery there were several competing libraries abstracting the browser inconsistencies: YUI (Y=Yahoo), prototypejs, mootools, dojo. So I'd say multi-handedly.


Eh, they have their place in history but jQuery was at least 10x more popular than all of the others combined.

Strong leadership without the bickering and bikeshedding that ruined its competitors.


I also remember Scriptaculous which at some point got somehow merged with Prototype and became Protaculous.


That's like, the hardest name I've ever had to read.


Reminds of the old days when Karma was named Testacular.


I started with prototypejs. I never understood why jquery was the one that really took off.


I agree, you can't talk about web development history without bringing up jQuery. That said, the moment was right for something like it to come up. The amount of boiler plate code needed to enable rich web experiences of the time went up with the popularization of AJAX, and it was inevitable that something would solve that pain point.


That's how I feel about the current state of web development. It really feels like the right time for something to come up and replace React/Vue/Angular with all of their myriad associated libraries for data, routing, etc. Something that is incredibly simpler.


Vue is already ridiculously simple; how much easier can it get? You don't even need to mess around with a complicated build pipeline, just reference the vue lib in a script tag and get going.


What I really want is it to be built into the browser so I don't have to use a library at all for the things React/Vue/Angular do.


I should also mention that Dean Edward's cssquery was the inspiration behind jquery.

https://en.wikipedia.org/wiki/JQuery#History


I agree - jQuery has done a lot to help inspire what querySelector and fetch are today (among many other things). The only cause for concern I have is what might frameworks in current vogue might do to influence standard APIs of the future.


I've only really worn a "web developer" hat twice in my career so far (both for internal tools), once in 2011-2013, and another from 2014-2015.

The first time around was rails with HAML/sass, with a light sprinkling of jquery used like CSS, mainly to make things like sortable tables, search w/ typeahead find, and a few other fancy things work. The second time around I used rails as a REST api and wrote an angular 1.x SPA for the frontend.

Honestly, the first time around was far, far nicer from a developer ergonomics perspective. Just writing your HTML in nice reusable, composable templates, even though there's a lot of scary abstraction violations being able to access @variables from your ruby controllers, was a very straightforward experience. And the jquery was used mostly like CSS with something to the effect of `$("input.search").search({...});` to just apply a jquery plugin to all css-selected elements indiscriminately. And you know what? It was pretty darned easy! Move onto the next problem.

My angular experience was far more complicated, and building the SPA was a level of effort on par with designing an entire application from scratch, with almost as much time spent developing it as I spent on the backend code.

You can talk a lot about how jquery isn't necessary because you can do equivalent stuff without it, and I'd totally agree, but it was just the perfect tool for what I needed it for at the time. Lots of awesome plugins to enhance (with graceful fallbacks) the views that rails spit out, without me having to write anything. Angular had lots of cool plugins too but the level of effort was just too high.


Moo tools...


Ya ya thanks John. Real subtle.


add gave us lots of devs who don't know how to use the DOM directly without jquery.


And don't get me started on people who have strictly zero idea about TCP/IP. Or silicon wafer design, for that matter.


Around 8 years ago I was on a project where my boss told me the web app I'd be working on was really slow, and they needed me to help them speed it up. When I took a look at it, I discovered the app was using a multitude of libraries with overlapping functionality - jQuery, ExtJS, Mochikit, YUI, and I think a few others. Every previous developer had simply included their library of choice when working on the app, and it had made the app overly bloated (and complicated). Definitely a good sign that browser APIs and their polyfills have become good enough for standard web app development.


How much of the reaction to this is: "isn't it neat that web standards have advanced enough that we don't need jquery anymore," vs a pile on of: "jquery teh sucks cause it's old and stuff."


The web has modernized. Browsers are kept up to date now more than ever. jQuery helped support antiquated browsers, but that niche is no longer nearly as prevalent as it once was.


Really? jQuery is not just about jQuery itself but its host of plugins make it very powerful. I still use some date picker even though input fields have supported date type but they look inconsistent across browsers and don't look as good as some of the jQuery plugins and it's just 1 example.


Certainly there is a lot of old infrastructure around jQuery. There is also a lot of infrastructure around Java's Swing.

But, the point isn't that those things exist or that there are a lot of them. The point is that jQuery's biggest value add, at the time, was it had a very consistent and fairly fast development across several browsers. In the bad old days, IE, firefox, and Safari all had vastly different and divergent sets of features. Heck, half of the stuff jQuery did was stuff you should be able to do with CSS but couldn't because of how differently CSS behaved across browser. This was one of the biggest value adds of jQuery. (I went through the bad old days.. they were hell)


I have created one of the decently popular jQuery light (3kb) alternatives: https://umbrellajs.com/

And I do not always recommend it, indeed for smaller projects you might be better off with plain Javascript: https://umbrellajs.com/documentation#native-methods

But native Javascript, as explained there, is more error-prone while jQuery (and Umbrella) are more permissive. Both have their pros and cons, but if you try to make native Javascript as permissive as jQuery you'll end up with a big mess. Unless you create some internal methods, which then you bundle, test, release, and... end up with another jQuery clone!


Modern front-end dev is all about over-engineering things with MVC libraries and whatnots, but for the love of God one shall not use jQuery.


It's all fun and games, until you have to access parent elements.

You'll likely start wrapping these methods, and before you know it, you have jQuery-micro.


That's what I have, a very small helper library that contains 5 or 6 functions that I use frequently like .closest(), .hideAll(), .showAll() etc.

My application doesn't use much JS so this seems reasonable to me instead of including a framework for a few functions.


For what it's worth, https://caniuse.com/#feat=element-closest is supported by everyone except IE (and Opera Mini, I guess).


That's exactly the point! "Oh, you can code [a polyfill] yourself, and it will work. Mostly. Sort of. jQuery bad, reinventing the wheel good! Never mind that you originally went there to implement some business logic, let's get tangled in the myriad almost-almost-working combinations."


> Oh, you can code [a polyfill] yourself, and it will work.

Use a polyfill that already exists. Take it out when browser support is there.


For finding parents matching a selector, there’s a fairly recent addition, Element.closest(). There’s not magnificent support for it yet (notably, no IE), so you will probably need a polyfill.


jQuery is actually one of the nicer javascript libraries.

- knows what it is, i.e. a web javascript module, it doesn't try to inappropriately wrap itself in CommonJS/AMDJS wrappers

- doesn't need node/npm to run

- doesn't need node/npm to build


However, it would be nice if I could include the parts I wanna use. Similar to lodash/underscore. Now it's either full jQuery or nothing.


You can do that by building it with only the modules you want: https://github.com/jquery/jquery/blob/master/README.md

There's also an official slim build without ajax and effect modules.


Just curious, does there exist a library that uses jquery syntax but with modern vanilla JS as the guts? i'm sure someone must have done this but i dont know about it. I'm interested to know if you could just replace the jquery cdn link for this and have your old jquery code still work?


Yes, cash.js[0] does almost that, although it doesn't mirror all of jQuery's methods (like .fadeIn() .fadeOut() for example)

[0] https://github.com/kenwheeler/cash/


Thanks! This is the kind of thing i was interested to find out about.


What do you mean by jQuery syntax? jQuery has a lot of features. If you mean the query selector you can do

    let $ = document.querySelectorAll;
If you mean chaining commands you can use the latest version of jQuery. It uses querySelectorAll under the hood.


FYI I believe it is generally considered better to prefer const over let if the value is never going to change. Prevents accidentally reassigning $ here.


True. I quickly threw that out as an example.


Yes i mean exactly that, but implementing as much of the jQuery library as possible, or certainly the most used parts. Was just a thought excercise.


I think maybe that _is_ JQuery.


Latest jQuery claims to support only recent browsers. I think it means that they are using relatively recent JS API without workaround or hacks if you're concerned about it.


Yes. It's called jQuery.


Zepto is API compatible, my own Umbrella JS (https://umbrellajs.com/) is not 100% compatible but it implements the most common jQuery methods


Or perhaps more succinctly, a JS polyfill library that uses jquery as the guts. I only mean that half jokingly.


The latest versions of jQuery provide a jQuery API implemented on top of current web standards.


I’m unsure about what goes on under the hood, but Zepto uses the jQuery syntax.


Nothing but respect for jQuery. It has had such a wide range of influence on both javascript and the browser ecosystem. The good thing about a great tool is that when the problems it solves no longer exist and can be retired gracefully.


> What did we replace it with? No framework whatsoever

They bragged, about the single worst web UI I have to use on a daily basis. Github.com combines the worst elements of static and dynamic web-pages:

- If something gets updated on the backend, it will update on the frontend

  - Except all the times it doesn't
- If you change something on the frontend, it will update on the page

  - Unless you interact with the page in any way after that, like changing tabs???
What you end up with is a frontend that uses a lot of AJAX, but still requires constant hard refreshes to see accurate information. It's an absolute disaster.


I assume jQuery itself will use this modern browser functionality. Making it smaller.


Well, they threw away the Sizzle selector engine once querySelector became available everywhere, but other than that… eh. I don't think they use fetch or Web Animations or anything like that.


Without comparison of performance "before" and "after" (in numbers, not words), this news doesn't have any sense.


I started my JavaScript career in 2011 with the two books "JavaScript - The Good Parts" by Crockford and "Professional JavaScript Techniques" by Resig.

Somehow all the time I'm doing JS, people were talking about how jQuery was "an old library" and "the old way to do things" even in 2011.

2 years ago I was on a JavaScript meetup and some guy, who did interfaces for stock trading, said: "We had to write our own framework, because jQuery just didn't cut it anymore!"

I just thought, no shit, it's 2016 and NOW you talk about replacing jQuery? Since its inception I used 4 different frameworks and even when I started in 2011 it was already "old news". Where have you been living if you had the impression there is only jQuery and "your own framework"


IMO, jQuery is still very usable for all the "almost static" web sites out there. Sure there are smaller and arguably better options out there, but there's no harm in using it if you're used to it.

I don't see why it being old is an inherent problem.


As noted by others, jQuery was essential in carving a path between the past of browser incompatibilities and the modern form of mostly reliable and evolving standards. It was hardly alone - other libraries did their part, evergreen browsers are essential, and the list of people doing a lot of thankless work is long and unassembled - but it was nonetheless an essential piece.

I want to clarify a bit about "JA Hate" though: Most of it stemmed not from JQ's limitations or age, but rather as a matter of architecture. While it's cool these days to smugly enjoy the options of vanilla JS, JQ hate was around before those standards were reliably implemented.

JQ really stepped in when dynamic web pages (i.e. pages that modify their own HTML without page refreshes) were becoming a thing. AJAX calls were new (to most) and exciting. form validations that didn't require 2-3 seconds to load, etc. All made far, far easier by the APIs JQ had.

BUT there were complications: JQ plugins meant that having multiple copies of JQ on the page tended to not work well - and that happened if you were mingling content sources. JQ didn't require it, but many coders would use the DOM to store data (JQ made it so EASY), which worked well short term but caused troubles. Example: If you have a list of items, with every other item shaded, and every item had some metadata in the HTML, and then you wanted to remove some items, what did you do? More importantly, when you wanted to restore them, where did it come from? If you were tracking everything in a JS variables and building the DOM, no problem, but if you were using the DOM to hold your data, you had issues. Even if you WEREN'T using the DOM to track your state, repainting all the DOM got expensive - a table of 10 items worked great, but a table of 1000 could bog down terribly.

Ultimately someone would inherit (or create) a convoluted mess of JQ and blame JQ rather than the creator.

Much of the JQ hate came not from JQ flaws, but the flaws of coding done in the face of JQ success (as has happened with so many languages/libraries/frameworks before and since). We've learned from those flaws AND successes though - querySelector() basically uses the sizzle syntax; modern virtual dom libraries deal with the DOM pains; be it React's Unidirectional flow or Angular's two-way binding, the goal is not to use the DOM to hold state; and every AJAX library out there tried for a better interface (arguably fetch() beat them all). We're still hashing out how to handle reusable pieces of non-static HTML, but there are many options.

So congrats to anyone that doesn't need JQ, and no hate to those that use it if they strive to use it well. I can only hope to write something hated for the results of success that nonetheless leaves the world better off.


As a vanilla-JS guy for 2 decades, I can say that you can go far without any frameworks, especially now.

The one feature I miss that jquery has is dialog boxes that can be customized with HTML.

Does anybody know of any cross-browser javascript dialog functions?


Right on! You may want to look into Sweet Alert, it's super easy to integrate! https://sweetalert2.github.io


I recently replaced jQuery on a project with a small custom DOM library. It cut more than 20% from the footprint of the application and helped to push load times on 3G under 3 seconds.

If you use some of the weirder stuff in jQuery or use plugins you might end up doing some targeted refactoring or just porting that code but I found it a relatively painless transition to make.

Tip: write unit/integration tests for the code you're about to convert as it makes the process much easier and faster.


The thing that I found surprising is their foray into web components: https://github.com/github?utf8=%E2%9C%93&q=-element&type=&la....

Custom elements are probably a great fit for .erb templates.


A bit OT: In my personal projects, it's easy to use plain JS instead of jquery. But as soon as I start dealing with object- and array-data (formally json), I cannot miss the underscrore.js library. At least without it, I start writing my own helpers for some actions on obj/arrays.


Don't you miss jQuery set-oriented operations, like $('.widget-item').removeClass('.selected')?

With querySelectorAll, you have to iterate over all the matching elements. Do you use some shortcut?


querySelector() will get you one element, otherwise you can use something like

Array.from(querySelectorAll('*')).forEach()

It is a little more cumbersome.


Yes, this is what I do, and I agree it's a little more cumbersome. That's why I asked ;-)


but is the page smaller/faster now? that's what matters


Apparently, yes. The author tweets later in the thread that the benefits they have seen include:

"Fewer kb sent to visitors, more explicit syntax when performing DOM manipulations, ability to use Flowjs for static type checking"


Surprised they are using flow, the new version of their Git GUI is written in TypeScript


The `$.extend` example seems a little overdone -- isn't `Object.assign({}, objA, objB)` a sufficient replacement for most uses?


The simplicity of the grammar is what counts here.


I actually meant to reply to https://news.ycombinator.com/item?id=17612990 , which mentions http://youmightnotneedjquery.com/ as a point of comparison between jQuery and vanilla JS. For some reason I thought that was the top-level article, not the linked tweet.


Great. How about removing the actual performance bottlenecks now? And the single point of failure.


jQuery really pushed forward the base plane for standards in the browser. It was a common well tested library that allowed developers more time in developing their app/game/etc rather than testing in browsers fixing standards holes.

Browsers are more standardized today because of it, but what will come in the future when there isn't a library as widespread to help that effort, probably more fragmentation and eventually more jQuery like libraries whether that is polyfills, vdom kits, wasm, based and more.

jQuery also created a rare simplification in the front end fast moving javascript eco-system that standardized a well tested across all browsers library that made front end development easier rather than more complex. There aren't lots of libraries like it today that look to make things more standard and simple rather than adding monstrous monolithic abstractions that are brittle to change, yet change every few months causing brittle/flaky development.

As a webdev that developed javascript before jQuery and all the others (mootools, prototype, scriptalicious even dhtml etc) it was a very welcome library and may not be understood how impactful it was to development speeds and a market standard that really helped ship products.

I feel like jQuery gets lots of underserved hate just like javascript itself does, meanwhile they are very useful, helpful and needed tools. Tools that simplify over adding more complexity are needed, some engineers just like to add complexity which makes them seem smarter, when the job of an engineer is taking complexity and simplifying it. jQuery simplified over adding complexity. jQuery always made team developments more robust especially with juniors on the squad, you could at least know jQuery was tested and focus on the implementation and app over internals/support/browsers. jQuery is a perfect simplified abstraction of common javascript needs that standardized development from signatures to usage and eventually browsers. Just like javascript itself which has simplified web apps and development, jQuery's simplicity and usefulness went well beyond the call of duty. Believe it or not, jQuery is still a good library and that is mainly because its mission is to simplify complexity. I feel like some of the hate against jQuery is because it simplified too much and people that like to add complexity felt it made them seem less than, comments like "it didn't even need jQuery but the samples were in that anyways" were because jQuery was a simplification and market standard most of the time, and that is ok, platforms are built from good cornerstones and libs you can trust just like native/browser standards themselves.

I do lots of projects, some with jQuery and some without, the ones with jQuery still seem to get less in the weeds of browser standards/capabilities than the ones without. Native js is much better by far but even jQuery uses most of that now. The other areas of jQuery like animation are not as useful anymore (CSS animations). However it is still nice to have jQuery at times because without jQuery, even with most of the useful tools available natively in javascript, it is a common signature/library that when not present still leads to other people making their own helpers and re-creating jQuery at least the useful parts i.e. selectors, event handling, ajax, dom etc.

Thanks jQuery and John Resig, we'll need more libraries like you in the future to bring front end dev back to sanity and see though standards fragmentation again one day, for now that is numerous polyfills and vdom kits. Let the best of the warring new jQuery's win. "The reports of my death are greatly exaggerated" - jQuery


No.


I hate when I see a javascript question in stack overflow and all answers use jQuery without needing it.




Applications are open for YC Summer 2019

Guidelines | FAQ | Support | API | Security | Lists | Bookmarklet | Legal | Apply to YC | Contact

Search: