Gov.uk drops jQuery from their front end
web.dev
web.dev
One story he told a couple of times was about some grey beard who was before his time. The grey beard was once a legend in the company, often helicoptered into projects at the last minute to help them squeeze out the last bit of performance. His secret was he had a mental library of assembly language tricks applicable to the hardware of his day. But every few years his tricks were less and less relevant as hardware changed and compilers advanced. One day the grey beard was helicoptered into my leads project and everyone expected him to get them some gains. However, this was new hardware and none of his old tricks worked.
I think of this story whenever I see jQuery popup on Hacker News. There is always a strong contingent of devs who swear by this library. But to me, they are like the old grey beard who didn't update his knowledge as the times changed. At one time jQuery allowed them to be the hero and "Get Things Done" faster than their competition. But times have changed.
Argue with me if you must but take stories like this one for what they are worth. The writing is on the wall for jQuery. I was writing websites before jQuery existed, during the reign of jQuery and still today. If some candidate mentioned proficiency with jQuery during an interview I would be polite but internally I would note that the person might be out of touch. Not a red flag, but a yellow flag that I would follow up on. Nothing worse than bringing on a guy who claims to be senior/experienced and it turn out his old tricks won't work because they are no longer appropriate.
But I agree I would not use jQuery in new project and when possible I would replace jQuery in existing code too.
This is still an ecosystem without a standard library and with no consistent design style/layout. It is janky and bad. It being "less bad than it used to be" isn't the shiny endorsement that everyone thinks it is.
It’s frustrating when people reject a good tool like jQuery, with the argument that the same functionality can be achieved with just vanilla JS.
This has worked for many years. I typically add a shorthand $ for the QSA part and on projects where I used to support IE11 you could add Array.from there but I haven’t bothered since IE was deprecated. jQuery does more but some of those things had performance impacts which were worth thinking about and the combo of QSA and fetch took care about about 90% of my projects.
document.querySelectorAll("div").forEach(i => i.innerText = "test")
>An HTMLCollection in the HTML DOM is live; it is automatically updated when the underlying document is changed. For this reason it is a good idea to make a copy (eg. using Array.from) to iterate over if adding, moving, or removing nodes.
So you need something that will also be efficient and correct, not a 5 minutes implementation.
It seems this only pertains specifically to overwriting the __proto__ of an existing object (the is the prototype of other things).
On https://kubirds.com I use:
jQuery appear: https://plugins.jquery.com/appear/
jQuery fancybox: https://fancyapps.com/docs/ui/fancybox/
Do not put jQuery to the trash yet, it still have a long life ahead.
Even scrolling down, and through the website, I didn't really understand it, until you compared to Nagios, which I am familiar with. Hope you don't mind a little unsolicited feedback. The website does look super clean!
I would love to read a paragraph of your elevator pitch the moment I lay my eyes on the site though. Cheers.
> I'm better than most reading poorer copy but I consider your(unchanged) copy very good.
This is nice to hear/read, yet I'm a perfectionist who knows perfection do not exist. The pitch can always be improved and clarity/transparency is very important to us.
> Unfortunately without the words"audit", "WORM" and"incident search" present or prominent I'm not your market.
This proves my previous point, since we rely on Docker images to implement the monitoring/reactivity part, literally ANY workflow/business logic can be applied (but we've been told that it's hard to trust "it can do everything").
> But I could think of many thousands of publication sites longing for your tool, if those terms applied.
I'd love to get in touch with you about that, if you have time, you can find my contact info in my profile: https://news.ycombinator.com/user?id=linkdd
You're talking past one another. He's speaking in the context of AAA games, and the equivalent of that in the webdev world is a highly interactive application.
I don't know what to tell you. The first sentence in my comment was a quote and the rest of the comment was responding to say how that quote was misunderstanding the OP.
I never said anyone specifically said to do that, but that, in the metaphor that the OP made, a static website isn't an accurate comparison to a AAA game.
I think the most diplomatic way of distinguishing the two types of programmers is just to ask why they like JQuery.
"Because it helps me ship faster" may be a bit out of touch.
"Because it's a required competency in working with some code bases" are probably the latter.
I said while yes that's true as a dev if I told you I needed you to implement a new payment provider for billing would you tightly and directly align with who we used or abstract it away via some wrapper so that if we ever had to change it wouldn't be difficult? Of course everyone builds abstractions so you aren't stuck with a single provider because it's crazy not to.
I see jQuery as that abstraction. At the end of the day each browser is an api implementer and while they've come so far, that doesn't mean the situation is stable and we'll never see implementation fracture again. It of course doesn't have to be jQuery but any direct implementation of JS seems to have that risk which is easily mitigated by wrapping the basic functionality. I don't know why you wouldn't choose to do it.
https://youmightnotneedjquery.com/ is a handy illustration of this.
Modern browsers have apis that are about as convenient as jQuery's, are standard across browsers, consistent with the language, and guaranteed to outlive jQuery the library. Aside from dot-chaining in a monadic sort of way, jQuery offers no benefit to the developer, while costing about 30kB of javascript.
There's absolutely no reason to believe that considering those APIs add new features independently of each other. A library like jQuery can serve as an intermediary if browser A implements new feature X that is possible in browser B but through excessive (and slow) DOM manipulation.
jQuery can act as a bridge between the time browser A's implementation and browser B's.
In practice, I'd much rather use the native APIs to do things in the browser than a wrapper library, because I find abstraction from these wrappers tends to get in the way as often as it helps. With modern JavaScript (for-of, the spread operator, far more array functions), it's usually only one or two lines more code to do things the native way, and I find it saves me a lot of complexity down the line.
You haven't seen the privacy nightmare APIs Google is trying to push on web "standards"? The only other two browsers, Firefox and Safari, are not going to implement most of them in the foreseeable future.
Unless something has changed about jQuery, it is only concerned with DOM manipulation and data fetching. Do any of the privacy nightmare apis touch those areas?
Are we really betting on Microsoft, Google, and Apple not getting into a feature fight again?
jQuery is the new Cobol!
I’m not a “grey beard” but I’m currently doing a freelance project updating the UI on a Perl+jQuery site… As much as we would like to rewrite it from scratch it’s very unlikely to ever happen, it’s going to be maintained as is with small steps towards “modernisation” over time.
0: jQuery is used by between 15-40x more sites than React depending source:
https://www.similartech.com/compare/jquery-vs-react-js
https://w3techs.com/technologies/comparison/js-jquery,js-rea...
It's not COBOL until something replaces jQuery that is easier than jQuery.
One line more. But you have one dependency less, which is quite beneficial
A lot of times the jQuery syntax is easier to understand (IMO).
Remove element exmample:
jQuery API:
$('.element').remove()
DOM API: document.querySelector('.element').parentNode.removeChild(document.querySelector('.element'))
or if you want to introduce another variable just to remove the element: const child = document.querySelector('.element');
child.parentNode.removeChild(child);
Create element example:jQuery API:
const fooElement = $('<div class="foo" style="display: none">')
DOM API: const fooElement = document.createElement('div');
fooElement.classList.add('foo');
fooElement.setAttribute('style', 'display: none');
I know which ones I'd rather write and read.https://developer.mozilla.org/en-US/docs/Web/API/Element/rem...
Also for element creation:
Object.assign(document.createElement("div"), { class: "foo", style: "display:none" });
I mean, you normally abstract these things with a helper fn or two, without importing the whole jQuery anyway.
Add enough helper functions are you're at jQuery anyway. Looking at the jQuery source code, it manages a lot of edge cases that I don't really have time to figure out on my own.
The DOM API isn't really designed that well for human consumption.
https://developer.mozilla.org/en-US/docs/Web/API/Node/nodeTy...
The DOM is at least very, very well documented. jQuery has documentation, but it's not even close. It gives away what jQuery always has been, which is a library that is aimed mainly at assisting bag-of-tricks StackOverflow programmers than people who actually want to understand their programs and the object graph they work on.
I really hate these exaggerations. jQuery is, last I checked, over 200k unminified. Anyone writing enough helper functions to get to a fraction of that is already a pathological case.
It's kind of like how you can comparing languages using simple example code isn't relevant because proper code with full error handling and edge case handling can be very different from a naive example.
The point is that this is a strawman. "Enough helper functions" to get to jQuery is 288580 bytes. A quarter of that, or even a tenth of that, is already a pathological case and way beyond almost every case of "jQuery substitution" that would happen in practice.
The worst thing about the web as a platform is the need to count bytes.
Nobody is reimplementing the 280k of jQuery as part of their projects, so no, you won't be "at jQuery anyway". That's bullshit.
It's not crazy that to accomplish what jQuery accomplishes without jQuery you're going to need almost the same amount of code as jQuery. It's not re-implementing the DOM -- it's a pretty thin but broad wrapper. If you don't need something, remove it.
https://github.com/jquery/jquery#how-to-build-your-own-jquer...
The whole point of using a library is to outsource the problem somewhere else.
I'm not calling jQuery is bloated or difficult to read, nor I am telling anyone they should count bytes.
> Is going to be a couple of one-liners? No, because jQuery hides a lot of complexity under it's relatively simple API that take a lot of JavaScript to reproduce. > It's not crazy that to accomplish what jQuery accomplishes without jQuery you're going to need almost the same amount of code as jQuery
Once again, that's my whole point.
What I'm saying is that jQuery isn't a 100-line library. The whole of jQuery is not being trivially reimplemented at several places. Projects reimplementing portions of jQuery functionality (a la youmightnotneedjquery.com) are usually only reimplementing very very few things, and are leaving out lots of stuff. Different projects have different needs, some people don't need the whole library, some do, others don't care. That's it.
The argument against jQuery is thus an argument against libraries in general. Why include any dependency that you only use a small part of? You can always implement anything yourself.
The counting bytes comment is because the web, as a platform, is very size-conscious. Rarely does anyone complain about the size of libc and how, since they only use file functions, that should just call into the Linux kernel directly.
Would we even by having this discussion if you could just tree-shake out all the parts of jQuery that you never use at build time?
Then it's a nice thing that I never made any argument against including jQuery or any library in a page or project, nor I'm saying anyone should reimplement it, or even do anything. I'm not talking about those things.
> Would we even by having this discussion
We aren't even having this discussion. Seems like you're having an argument against an imaginary version of me. I'm not saying (or implying) the things you are arguing against.
Reminds me of the warning about rewriting old "messy" codebases. I am paraphrasing, but the upshot was "You know what those weird and ugly bits of code are? They're bug fixes, and they were earned through sweat and blood and years over a period of many, many years."
JS is design by a committee full of people afraid to come out as "not-as-kind" and completely detached from reality.
True, doing some of the things which were half an hour on stack overflow or 1 line of jQuery became a couple of lines of vanilla JS but the API is still pretty awful.
Think about XHR > fetch vs $.get or $.post
I agree, I'll try to use vanilla JS and google something when I need to ship some code - but for hacking around I'll just bring in jQuery and write 1-liners at blazing speed.
var xs = document.querySelectorAll('.x');
for (var i = 0; i < xs.length; i++) {
xs[i].addEventListener('click', function() {
this.style.display = 'none';
});
}
jQuery: $('.x').on('click', function() { $(this).hide() });
ಠ_ಠ document.body.addEventListener("click", ev => ev.target.classList.contains('x') && ev.target.hidden = true);https://gist.github.com/pseudosavant/b86eedd9960ade958d49447...
These threads are completely ridiculous.
Maybe it's just me but with all the rampant age discrimination nowadays in tech, I really don't like to see the continued propagation of this stereotype.
All sorts of people of all ages are unwilling or unable to update their knowledge of new tech, there is no reason to link this characteristic to someones advanced age.
If your answer is that 'it's just part of the story'. Well that's precisely the complaint.
It simply means someone experienced/being at something for a long time. The greybeards at a company can be all women of the age 26, but if they been with the company for 5 years when the company got started 5 years ago, they are the greybeards of that company.
Might as well say "veteran" or "old-timer", although "old-timer" would imply actual old age, "veteran" implies nothing like that.
Greybeards is an inclusive term and it's a well known term.
What I have seen is awkward situations where you have two developers of roughly equal competence. One happens to be 45 and the other 28. Fine, nobody would care about that. Except that due to automatic annual raises, job switches, seniority bumps etc, the 45 year old developer is paid twice as much as the junior.
The rational response to this would be to say to align the two salaries (probably somewhere in the middle), but obviously the older one is never going to accept that - we all expect our salaries to "ratchet" upwards. So we end up with the irrational response, which is to sideline/kick-out the old expensive developer
That, to me, says there's plenty of ageism.
If it was as simple as "they ask for too much", then someone would snap them out of it and we'd see plenty of older devs at software companies. Maybe less than younger devs, but plenty anyway.
Honestly, I'd prefer if there were more older engineers to show the younger ones how dumb they are. Maybe better at building dynamic frontends, but dumber. That kind of seniority is sorely missing in software engineering, and it would drive standards upwards rather than downwards as they currently are.
I'm currently in between, and wish I had more mentorship.
I agree with you here - the question is why? I don't think it's because we're discriminated against for being old, I think it's because in 99% of cases (we can't all be donald knuth), our cost grows faster than our skills. So we either move to management/business (where experience matters more and it's much harder to quantify productivity), or we become "the overpaid one".
> If it was as simple as "they ask for too much", then someone would snap them out of it and we'd see plenty of older devs at software companies
But they wouldn't snap out of it. (a) in most countries you can't demote people, (b) it's very hard psychologically to accept being paid less for the same job
> more older engineers to show the younger ones how dumb they are.
I'm talking about 45+ vs 30 years olds here, not 30 vs 23.
I think a major factor is that the field just exploded so much over the past 20 years. Statistically, people over 40 are going to be in the minority.
I also do think a lot of startups maybe aren't the best place for older people. My brain wastes a lot of cycles on edge cases I've learned to identify from experience, that don't matter if you just need to slop some shit out the door ASAP.
Following from that, it's easy to imagine that a bunch of the older engineers that you don't see at software/tech companies have in fact graduated into extremely well-paid, long-term roles working on software for banks, insurers, utilities, resource companies, whatever.
Seniority bumps, x-weeks-vacation-after-y-years-of-service reward that intangible.
Yep, especially culturally rather than financially. Almost everywhere I've worked there was the implicit assumption that engineers graduate out of coding jobs into management roles. In a lot of places there's the idea that focusing on writing software is some sort of career dead-end for older people which is a shame for anyone who just likes coding. I think it's widely perceived as a young person's job for no good reason.
And on the business side it's also pretty blatant. IIRC founders in their 40s are statistically most successful. Yet prominent people in the industry still openly fetishize youth.
But you kind of do have to be old in order to have outdated knowledge: nobody young is going to learn assembly tricks which worked on MIPS and other past architectures. Older devs and companies not constantly learning new things and updating to best practices is a real phenomenon.
On the other hand, anecdotally most older developers actually do keep up to date with the latest best practices. And there are lots of decades-old frameworks which aren’t obsolete: lots of people greenfield projects with C++ and Spring Boot and .NET, and unless I’m mistaken the C ABI and system calls haven’t changed much over the past ~40 years. So it's not like being old automatically means or even really suggests you're going to use worse, outdated techniques.
I'm not so sure. Google and StackOverflow are chock full of outdated (sometimes dangerous!) advice and knowledge on just about any tech subject, which hurts the young as much as the old.
I've seen just as many outdated suggestions from junior devs repeating the first thing they found on google as I have older devs with stale knowledge. I'd probably argue the former has been a larger problem, honestly.
Not in the frontend dev space. I once left it for 2 years. when i came back it was a whole new world
If any student leaves that program with a modern perspective of web dev (such as using Redux or even RTK), it will be due to their own personal grit.
C'est la vie.
No, this generalization is quite correct. If you went to a bootcamp which was not such as Hack Reactor, then perhaps you may wish to promote the program by name and discuss your experience there.
Hack Reactor has made Redux completely optional and so almost nobody choose it for their projects. This may have been in response to transitioning to an online-only program. If students understand anything on the "React ecosystem" including even Redux, it is due to their own personal ambition. If you see Redux explicitly listed in their curriculum, do not be confused.
If you see students with Next.js, RTK, or any other framework or library from the React ecosystem on their portfolio, that is due to their own grit.
I've also seen the opposite of what you'd expect: a young startup with a very young team that functioned on outdated practices and tools. My first contact with their codebase was a shock to the system – a mishmash of competing coding styles and conventions, barely any of them a best practice, much of it not very idiomatic, an alarming lack of consistency. The choice of tools, libraries and frameworks was (by startup standards) definitely not best in class, and where good choices had been made, the joy was short lived by realisation that they were on old versions, or not using their tooling properly.
But, anecdotes aside, there's a point that generally gets overlooked. Best practices and good developer experience are the result of intentional choices, often in retrospect. The only way to come up with best practices or to improve DX is through experience -- especially poor experiences. I mean, who would've thought that experience was an asset.
As an old guy I would find it very hard to keep up to date with the "latest best practices" because I tend to think of "latest" and "best practices" as antithetical. JQuery is a good example: I never invested time in it since I figured it would pass. I could smell it from the way kids were raving about it. So this type of article foreshadowing its demise is nice to see. Like when you drag your feet on some looming deadline at work and some force majeure makes it completely irrelevant.
Either that's wisdom from an older dev that has been burned in the past or that's just an old dev set in his ways. Take your pick. ;-)
To be sure, when I began a good dev was good at memory management (ha, ha).
More recently, a good dev is one that is good at concurrency.
New devs might not understand memory management, should they though? Has everyone come across (at least once) where a junior dev creating an "integer object"? Or perhaps an object to represent a character?
When I began I rarely even saw a single secondary thread in code, very rarely saw the need to create one. Then again, one core machines so.
I can see how my choice of wording created an implication that people who have grey beards are old and that it is this oldness that contributes to their unwillingness to learn. The familiar cliche of "you can't teach an old dog new tricks".
What I actually hope to communicate is that there is a hubris which leads some to believe their skills do not require updating. The caution is that sooner or later this hubris may lead to sudden downfall. People may call on you in their time of need and you will fail. And this failure is not because of your age, your intelligence or your willingness to work hard. You will fail because you became overly comfortable with a passed status quo and you let your skills get out of date.
I see a trend of well-written, evidence backed articles where large, well funded sites are making a case to deprecate jQuery. These fact-based investigations into problems faced by their dev team result in a reasoned decision to remove a dependency that no longer justifies its cost. I encourage everyone to introspect if their defense of jQuery is on an equal technical footing to these types of investigations.
But speaking as someone who writes vanilla by default, it really really isn't as big an issue as you think it is.
You are wrong.
This is a strawman argument. It's a biased view you hold. Because of that, you make up a story to match your biases around people who use such-and-such library don't think they need to update their skill set. I'm not angry about this, but am only pointing out biased arguments create dissonance.
> I see a trend of well-written, evidence backed articles where large, well funded sites are making a case to deprecate jQuery. These fact-based investigations into problems faced by their dev team result in a reasoned decision to remove a dependency that no longer justifies its cost. I encourage everyone to introspect if their defense of jQuery is on an equal technical footing to these types of investigations.
You read something somewhere about how jQuery is a costly dependency. Yet, there are no links that I can see anywhere in the threads here, nor a good rational argument for people to NOT use jQuery because it is a costly dependency. There are opposing opinions on this, but the opinions that it needs to be included via CDN don't address the fact it can be hosted locally and the opinions "who needs all that code to load?" don't take into account that browsers and networks are bonkers fast nowadays. Who cares if it's a bit more code? It's not like jQuery is growing its codebase at the rate compute and network speed increases.
For that matter, could not the same argument be made of JavaScript itself? I taught myself Promises, not because I could stay "relevant", but because it makes good sense to write code that is easy to read and maintain, even if it is me doing both on my project. The code I produced when I wasn't doing Promises was "legacy" the second it hit the repo, and will be "costly" if someone else has to jump in and work on it to convert it to Promises, because they'll have to brain dump what I was thinking (or not) when I wrote it!
This salt and pepper beard stays up on technology. I didn't really write code in the past, but now I'm great at what I do and I fully intend on exploring new technologies when they compliment what I can do rapidly in the frameworks and methods I well understand, if that's what it takes to get to market faster.
Well, Gov.uk for one, as per the article you're commenting on. As they pointed out:
> Not everyone is tapping away on their 2022 MacBook Pro on a rip-roarin' broadband connection. GOV.UK has to be accessible to everyone, and that means keepin' it lean.
> Here's a few of the greatest hits from Matt Hobbs on what GOV.UK noticed in removing jQuery:
> - Less front end processing time overall.
> - 11% less blocking time at the 75th percentile.
> - 10% less blocking time for users at the 95th percentile. These are users who experience seriously adverse network and device conditions, and every performance gain matters especially for them.
If you're making a game, say, you may (may!) not care if Edna can't load it on a 1993 iMac, and you might be loading 40MB of resources, so another 24kB is not your pressing problem.
Engineering effort is always in short supply, and it is very expensive. Use it wisely. Sweeping judgements gleaned from very different products may not apply to your case.
> This is a strawman argument.
I'm not sure I follow. It reads to me like the original commenter is arguing that jQuery supporters have out-of-date knowledge. What's the strawman? jQuery supporters?
> his knowledge
Women are programmers too, and there are older ones out there maybe shaking their head at this type of judgement.
To try to shoehorn this back into the compiler analogy, modern frameworks would be like the advanced, complex and opaque compiler, and the grey beard is the guy that understands how stuff like HTML streaming and font download prioritization and hidden classes affect performance, whereas the team lead is analogous to the run-of-the-mill bootcamp grad that knows how to use the framework-du-jour but is way out of their depth if venturing outside the comfort of the framework and into the depths of those advanced topics.
And I think the gov.uk use case here might actually be an outlier in the sense that it actually considers performance of an already tight codebase, whereas a lot of jQuery deprecation efforts bring with them heavier alternatives in the name of maintainability or developer productivity or hiring or whatever. To be clear, many of these concerns are quite valid, but it seems a bit disingenuous to create a false dichotomy between understanding of low level concerns vs concerns about SDLC management. They aren't mutually exclusive.
If your expertise is in low-level browser performance but you lack deep knowledge of React/etc, your skills aren't of diminishing relevance, and probably won't be for a long time.
Something like Angular.js is a more apt example of a skill people still do advertise as a primary thing in their resumes these days and it most definitely plays into the diminishing relevance thing. On the other side of the spectrum, you have newbies writing down "HTML/CSS/Javascript" in their resume, which basically screams zero experience (aka "low/no relevance until they learn to speak the cool framework lingo"). There are plenty of other quote and quote "uncool" skills in actual resumes. Flux. Sagas. Ember. Etc.
So, yes, an argument can certainly be made that recruiters/interviewers do "discriminate" against various stereotypes to various degrees, and it isn't necessarily always based on ageism. A recruiter that reached out to me recently had an interesting term to describe this phenomenon: "skill commoditization", aka looking at people as snapshots in time, and evaluating some skillsets to be intrinsically worth less than others, even if they have some amount of overlap, instead of looking at people as malleable entities. It's worth thinking about how treating developers as commodities might hurt your hiring, especially if your hiring revolves heavily around evaluating for expertise in a specific framework.
> Maybe it's just me but with all the rampant age discrimination nowadays in tech, I really don't like to see the continued propagation of this stereotype.
I would agree. If you last a long time in tech, you're more than the sum of the libraries you've learned.
In 1998 I was in a web development class with a guy, and one time I went by his house and he showed me his little resume site he was working on. It was really nice looking, he had a great sense of design, I could have made it but I couldn't have designed it. But it was all table based, so I showed him CSS and extolled its virtues.
After which he exclaimed furiously "That's the problem with this industry, there's always new things to learn!"
He was just starting out and was already unwilling to update his knowledge of new tech!
I think he's working as a SiteCore admin in Dental association now. I'm pretty sure he has a nice work life balance, so make of that what you will.
> old trick's won't work
> writing is on the wall
jQuery still works and is used in an crazy amount of websites. It's not going away soon. The biggest downside is the extra network request, but it's probably cached in 99% of browsers, so all that's left is some extra CPU time.
You're also exaggerating the claims of jQuery defenders. No one here is arguing that the site should keep jQuery, or that you should write a ton of new jQuery code.
It is just a tool in the belt for an engineer. Can you use jQuery in 2022 or later to solve really amazing problems that impact user experience? You sure can! Would you be better off to use a modern javascript variant and stuff like react instead? You also absolutely would.
So just because a tool is old doesn't mean it can't be used to solve real user problems. There are still banks and airlines that run COBOL, and as a user, do you really care that much? I'd take "knows $insert_older_less_hip_tech_here" as experience of having done something for awhile.
Now if I was asked to write a front end today, I'd have to sit down and properly learn react + typescript (because javascript is awful without sensible type checking), and that would add to the time to ship, but is the correct thing to do.
Over the past 15 years or so browser JavaScript engines, except at the extreme edges, are roughly comparable. Further, a lot of the features of jQuery have been adopted into standard JavaScript.
So, the reason of eschewing jQuery, even for small pages, is simply that you don’t need it. Vanilla JS (or typescript) + modern CSS have pretty much all the same capabilities without any of the bloat. Using it today would be a little like using a library made to back port java 8 features onto a java 5 JVM.
And let us avoid some of the extremely verbose and un-ergonomic standard APIs.
The reason we're not discussing them today is that jQuery has a stupendous API that simply hasn't been matched yet.
The react part is just for when you need to build something that needs architecture.
Why?
The reason jQuery was so successful, is still so widely used and was instrumental in fomenting HTML5 and killing Flash was its API. Nothing has come close to it in terseness, elegance and power.
Just skim this thread for examples.
It really is enjoyable working w/ react+typescript. :)
"Nobody goes to that restaurant anymore, it's too busy."
https://dictionary.cambridge.org/dictionary/english/veteran, https://www.oxfordlearnersdictionaries.com/definition/englis... both give its primary meaning as "a person who has had a lot of experience of a particular activity" or similar. Even Wikipedia gives the generic definition first, and clarifies the more specific case as "military veteran".
A long time we had a really good engineer who can crack topcoder and coding challenges with ease. We had a problem where we had to collect all changes to the User models and send it to the marketing platform. It was initially implemented in Rails Active Record which took progressively more time to collect and sync changes. Rails was hot at the time and SQL was really frowned upon. A lot of developers to this day hate SQL. Then came a "grey beard" who simply rewrote the whole thing into a single complex query that let the database figure out the optimum way to find the exact same data. Total time went from over 10hrs to 10mins.
Whenever I want to use "vanilla JS" I use jQuery, because I find the DOM and various other JS APIs quite annoying to work with and jQuery makes things a lot smoother. There are some other, slightly smaller, libraries too, but they offer little advantages, are often unmaintained, and many people at least kind-of knows jQuery.
Bombastic absolute statements about "greybeards" being "out of touch" etc. is basically why I tend to avoid the JavaScript frontend community by the way, and also why I moved towards backend rather than frontend. I'm too old to deal with people who think there is One True Way™ to do things and that everyone who disagrees is a blubbering idiot (not that FE JS have a monopoly on this by any means, but it's far more common there).
However devs seeking employment should always be prepared to play up to what is trending vs what is appropriate.
You see, new hot technology is always replaced by another newer hot technology, and after hotness wanes, projects often become a abandoned and unmaintained.
Extra this if the proposed hot new tech comes from Google. In this case person pushing it should not only be stopped, but also slapped hard, to help come back to senses.
I think your portrayal of well-seasoned engineers as the derogatory 'greybeard' with a 'bag of tricks' and a hero complex -- glosses over the fact that many of these men and women have real hands-on experience with a multitude of technologies spanning decades, and in my mind there's real value / leadership qualities associated with individuals companies can rely on to just "get things done" in a pinch.
The assembly tricks got obsoleted because they're not needed anymore - we simply don't program in that hardware anymore.
jQuery still works fine to this day. It's just that engineers don't like it anymore. The same will happen to React in a few years.
I wouldn't hire a jQuery developer for working in a cushy company with their millions and their React codebases - React knowledge is actually one of the things we test for (and, unexplainably, one of the few exceptions we'll allow to avoid knowing about algorithms and time complexity).
If I had to build something with my money on the line, I'd definitely pick the jQuery veteran.
It doesn't sound like grey beard knew what he was actually doing, but more relying on his years of experience and good fortune that has kept him with a job up until then.
Jquery is also a library not unlike any other a la react, redux, observables etc.
Jquery was successful but now there are better more powerful tools.
Lots of jquery can now be done natively or with better tools.
Recently I helicoptered into a call with three developers trying to execute a database upgrade and it seemed to be hanging. I joined the moment when they wanted to interrupt it and try again for the third time.
Only thing I asked was, if something is locking the schema. Then I left to another meeting and I saw them exchanging statements to find locks and delete them in the chat. Turns out there were long running queries hanging that nobody seems to care about. To me it's hard to believe nobody has configured a query timeout on the database
Can I ask you about your current webstack?
And for React: https://javascript.info/custom-elements
$('.sth').closest('ul')
To me jQuery is like Regex or Linq. I think it had a really good api.https://developer.mozilla.org/en-US/docs/Web/API/Element/clo...
So the actually drop-in replacement of `$(foo).closest(bar)` would be something like:
Array.from(document.querySelector(foo)).map(el => el.closest(bar)) document.getElementsByClassName('sth')[0]?.closest('ul'); Array.from(document.getElementsByClassName("sth")).map(e => e.closest("ul"))
The jQuery is definitely nicer to read than this thoughI personally have tried to drop jQuery, but truthfully, its syntax is just much easier to use. Nowadays, I use Cash https://github.com/fabiospampinato/cash to give me the nice syntax without the bloat. It strikes the perfect balance for me.
Went from disliking it to really liking the syntax. Its pretty clear and easy to use, which is why I still use it. We don't use it extensively becaue we're still on the "submit form, get page back with javascript graph and data tables table, development model. We probably should transition to a framework, but they evolve so quickly ...
It's not just the syntax, it's also the expression-heavy and chained API which makes it much more flexible. As well as the set-oriented approach, which can lead to performance issues if you're not careful but is generally extremely enjoyable.
The DOM is an extremely procedural, plodding API, you need to name everything because you always need to set attributes and call non-chainable side-effecting APIs, not to mention the fecking NodeList which has to be converted to an array to do basically anything useful (in part because Javascript never really embraced iterators, and instead uses arrays for everything still).
I guess you could mitigate that with an "API adapter", but...
A lot of API with long names is no longer a issue to type. You just mark the variable as a element. After that, autocomplete handles the rest for you. Shorten the gap with experience of using jQuery. If developer tools is still as dumb as that era. I would think the transition is impossible.
And there are also more frameworks to enhance experience of style modification or templating. Back to then, there are only some dumb template that do initial rendering. But framework these days also handles update for you. So you don't really need to modify it directly by yourself unless in some edge case.
While this is true, I can still code circles around frontend developers using vanilla JS.
The decline of jQuery is mostly due to the rise of webapp frameworks like React and Vue. But if you are tasked with adding like, a button to a static webpage, jQuery is still the king.
Only thing I always have to look up is how to make sure my script is executed once everything is done and not before and "ready()" is obviously easier than adding an event listener to "DOMContentLoaded". Yeah, had to look it up for the comment.
$(thing).doThis() is just so perfectly terse and understandable for what it's doing. Not just writing, I find jQuery to be very, very easy to understand and read.
My first use of jQuery was in the dark days was building UIs (with things like drag and drop, etc) that had to run on Internet Explorer and Netscape. We'd started with "vanilla" but were ending up with what was effectively two separate codebases. Moving over to jQuery let us eliminate a massive amount of duplicate code and dramatically increased our productivity.
Partly. Frameworks like Angular/React/Vue are a necessary byproduct of building and maintaining large codebases. But the fall of jQuery was largely a result of a more standards approach in mainstream browsers (said another way: deprecation of IE and not needing to work at maintaining consistent behavior across browsers), as well as adding traditional jQuery-like features to vanilla JS.
There really isn't a big use-case for jQuery anymore, although I will remember it fondly.
I still wonder occasionally if there's a place for a library that works like a strict subset of jQuery, but with different error/empty set handling defaults. Especially with list comprehensions. I found that 9 times out of 10 if I run a selector I'm expecting results, and jQuery will silently eat that error, requiring a bunch of inline error handling in the 'interesting' paths in your code. I'd be much happier with an optional parameter for silent failure or even writing the occasional try/catch.
I use a module "dqs.js" for all my query needs. It contains only these two lines:
export const dqs = document.querySelector.bind(document);
export const dqsA = document.querySelectorAll.bind(document);
And use it like this: import { dqsA } from 'lib/dqs.js';
for (const rabbit of dqsA('#rabbits .green')) {
... do something with all green rabbits ...
} document.querySelectorAll('a').forEach(tag => {
// operate on tag
})This is something every web dev will instantly know what it does:
document.querySelectorAll('#rabbit .green').forEach(tag => {
})
Whereas this is something nobody knows what the fuck it is because it's completely non-standard. for (const rabbit of dqsA('#rabbits .green')) {
}
And get what, 10 characters less in one row? Basically nothing.All they did was alias `dqsA`. If anything, it's the fn name that could be better.
Most IDEs will allow you to see what dqsA aliases by mousing over. I don’t really see a problem with it.
It also looks like the kind of thing a pre-commit hook could trivially expand if you’re working with other people who might find it in some way unacceptable.
A lot of people don't have control over the content of their site in enterprise situations. If you're stuck using an old framework or CMS you could be beholden to someone else. And at the same time there's a lot of devs who dgaf and just ship what works.
"#some_combo:has(option:selected[value=..]) + .." seems like a reasonable way to conditionally target something to me, is it terribly worse than some other way?
Yeah, it's fragile and will easily lead to bugs when someone changes the markup without realizing it's going to break some crazy selector in another part of the code.
It would make a lot more sense to just add a class to the element you're trying to select.
Look, if you need this for some one off thing and you've determined it's the best way to do it in this special case, it's not hard to create a function that will find the element you want.
It's not a good argument for using jQuery IMO, because if you're doing this regularly there's probably a better way to do it.
But coming soon™ you will be able to do even this with `document.querySelector`.
Edit: I didn't pay close attention to your second example. I was speaking mostly related to the a:has example before. Your second example seems to be something that would be desired more in CSS than JS, and I don't think it's unreasonable to do that in CSS. If you need to do it in JS you can workaround browser limitations just fine by writing more than one line of code to do the selection and test the condition.
https://developer.mozilla.org/en-US/docs/Web/XPath/Introduct...
[...document.querySelectorAll('a')]
.filter(node => node.getAttribute("data-foo") === "bar")Not sure why it caught on.
Might also have something to do with Redux and immutable patterns. (the use of spread operator in general)
and you can querySelectorAll('...').filter(el => ...) without any copies.
and you can querySelectorAll('...').filter(el => ...) without any copies.
ditto for other mentioned functions. Prototypal nature of Javascript is there for a reason.
const $ = (selector, parent = document) => parent.querySelector(selector);
const $$ = (selector, parent = document) => parent.querySelectorAll(selector); /**
* @param {string} name
* @param {HTMLElement.prototype} props
* @param {Array<HTMLElement|string>} children
* @return HTMLElement
*/
function $h(name = 'div', props = {}, children = []) {
const el = document.createElement(name);
Object.assign(el, props);
el.append(...children);
return el;
}Jr devs have the tendency then to discard jquery because "is old" not because it isn't working anymore.
Unless of course I need to support legacy browsers, then jQ is a no-brainer - that crap is solved there and I don't want to have to deal with it myself.
And while jQ is large compared to my little home-grown set of wrappers, it is small compared to all the other stuff many pages draw in these days, so perhaps size isn't a great metric to criticise it on!
Companies are getting more security-conscious because of all the hacks and the pain of keeping old browser support is no longer outweighing the risks of upgrading is my theory.
That said, front-end frameworks can of course be a better choice for many things, even if it's just because it provides this kind of organisation by default making it easier for the, ehm, less organized devs.
PS. $ is an alias for document.getElementById so you can just do $('my_id').style.display = 'none'.
See, it turns out that by carefully leveraging cached retrieval of third party resources, scripts on two different domains can figure out if they are running in the same web browser, effectively pulling off browser fingerprinting.
To stop this, modern browsers don’t share third party resource caches cross domain.
So using a well known CDN no longer confers any benefit - even if a user has pulled down jquery for another site’s benefit, when they come to your site and you request the same resource, the browser will go out and re-retrieve it, to prevent you or the third party domain from being able to infer anything about the user based on the speed of the response or whether or not the request got made.
document.querySelector('#element').style.display = 'none'
That has the same ergonomics as the jQuery selector, and is just a bit longer. I feel like with editors that autocomplete, it's not enough of a difference to warrant the extra dependency.
I've never used JQuery before and would have assumed calling .hide() on an element would set the CSS attribute "visibility: hidden" rather than "display: none"
Nitpick: This crashes if #element doesn't exist, while the jQuery one does not. Also, the jQuery selector is a tiny bit more powerful (:even, :odd).
IMHO, jQuery is good for what it's built for - a nicer interface than vanilla - but the main use case is much less needed now that frameworks exist.
If it's meant to be the case that the element may or may not be present, then I'd much rather see an explicit check for that, than assume one thing and find out another later.
But I still prefer vanilla or anything but jq
with vanilla, it would be just typing a bunch of extra properties.
The main problem I have with jquery though is there's no convention for event binding, so there is literally no way to know if an element depends on a jquery event handler without grepping the js for every class, id, and data selector on the object. Even that doesn't always help. This makes it almost impossible to remove jquery from a project without breaking it.
Alpine or stimulus do a much better job of filling the event handling holes that still exist vanilla js. Dom traversal/manipulation in vanilla js is good enough, even if it isn't 100% as good as jquery.
I have had such a positive and lovely experience with it. It's the reactivity I've always wanted; ie plays nicely with VanillaJS without imposing a complex build process.
const $ = document.querySelectorAll.bind(document)
Then later:
$('#element').whatever
I used to be a big proponent of jQuery especially in the heyday of shims and browser hacks, but in the last few years I find it often gets in the way of what I'm trying to do. Now that the native browser APIs are maturing and relatively consistent, having direct access to the objects and their properties is simply more predictable than having to second-guess a layer of abstraction that does the same job but differently.
I have to remember, what does jQuery's .hide do again? It doesn't just set display to none or visibility hidden. Give it a duration, and it will use the style attribute to manipulate the display, width, height, opacity, padding, margin, etc. Then it leaves some style properties behind. Ugh. Do I really want to do all that stuff? Do I really want to build my UI framework around jQuery so I can avoid annoying transition artefacts?
Not hating on jQuery. Just my own experience. I used to feel liberated when using it because browser APIs were so terrible but now I feel encumbered if it's included as a dependency on a project I'm forced to work with, because it does so much black box magic. If you avoid certain things and stick to what it does well then it's not bad, but then there's no point using it because what it does well is no longer a pain point in browser APIs.
For me the main thing it excelled at was DOM selection and manipulation. Native does that just as well now. The secondary benefit was animation, which these days native CSS can go a long way without excess verbosity, and if you really need a more feature rich animation library I've not come across any better than Greensock for getting the job done, even if it does have a paid tier, though I am sure there are dozens of other libraries equally suited for animation, the point is that is not jQuery's strength either.
Anyway circling back to what you were saying, efficiency-wise, for any complex animations jQuery isn't the best tool for the job. For DOM manipulation native can be just as easy with some sugar. It can do a lot of unexpected and hidden things most people aren't aware are happening, so many bugs and time wasted realising jQuery was messing with style attributes that break an otherwise well designed layout.
I would rather write a few characters more code or a couple of lines more to have direct control over what's actually happening. That seems more efficient to me.
Edit: Ok on reflection I guess I am against jQuery, but I don't hate it. Using it these days just feels like trying to figure out how to get it to do what I want to the underlying APIs, when I could more easily and predictably just be manipulating the APIs directly.
export const hideElementById = (elementId) => {
document.getElementById(`#${elementId}`).style.display = 'none'
};
Or perhaps export const toggleElementById = (elementId) => {
const element = document.getElementById(`#${elementId}`);
const newDisplayValue = element.style.display === 'none' ? 'block' : 'none';
element.style.display = newDisplayValue;
};I currently work with B2B applications in a sensitive banking context, so any time I can feasibly remove a 3rd party dependency it's almost certainly getting removed.
The extra LOC and time overhead is more than worth it for us. We get dinged on older products which do use jquery all the time by our customers who insist on using other 3rd party security scareware to light up random parts of their infra. I can't use 'but its elegant' or other technical handwavey bullshit as an excuse when the Chief Security Officer of Bank of America shoots me an email, even if there is zero chance the detected "vulnerability" would actually pose any risk in that particular context of use. Certainly, we could spend the time & energy fighting for exceptions, but its way easier to write a few extra lines of JS.
Don't forget the performance angle either. If you are doing a lot of element selection in a hot loop, document.getElementById can be orders of magnitude faster than the jQuery alternatives.
What's the "modern" alternative to jQuery in that regard? I don't do much JS development, but if I needed to make an AJAX request today, my first instinct would probably still be to use jQuery.
Unless this team perfectly did a 1:1 replacement of jQuery calls with equivalent native JS functions, this isn't "removing a 30KB dependency reduced blocking time by 11%."
It's "we rewrote our JS and it reduced blocking time"
There's a lot of willful blindness about cost structures. If it were just one or two people you might conclude that folks are trying to sweep things under the rug, and when I was just starting out I did feel that way. But it's so consistent that I often end up bonding with people who don't feel that way, without putting Dunbar's Number into any sort of danger.
One of the hardest "Code smell" issues I've had to contend with is the habit of people to spread out problems so thin that you can no longer see them, because they're everywhere. Like being in a room with a bad smell, eventually you can't detect it without a major change of perspective. Even though everyone new who comes in starts with, "what is that smell?"
11% of your blocking time on a library could be a perfectly reasonable *budget*. The mistake is not having a goal, or assuming the goal is zero. Zero is dumb, because if that's your target then we'd be talking a static HTML page and then why are they paying you? So what's your real budget? And given that budget, what's a reasonable proportion for different concerns? 1/9th spent on a library is probably a bargain.
They do claim a "reduction in JS size" on all JS apps "between 31% and 49%."
Speed really isn't bad, and it's so straightforward that it's hard to mis-use at this point.
I seem to have way more issues with newer frameworks/SPA if I'm not using chrome with no extensions.
Makes me nervous dealing with important stuff like banking or government sites.
Vanilla js for similar things just looks like someone has waved the ugly stick at it.
There are sound arguments against jQuery but the "you can just use vanilla" is the least convincing.
Even GOV.UK, an incredibly lean website by today's standards, only noticed a 10% difference in their benchmarks.
Cue all the people going on about big O for parts of the code that are indistinguishable from noise in actual benchmarks.
The primary use case for it has been cross browser compatibility plus a bit of sugar. The former is _gone_ and the latter is easily replaced with a few lines of JS. Then there is an ecosystem of libraries and components around it. Many of them have ditched jQuery or have provided an API that doesn't require it.
I think if you strip out the AJAX support it can get extremely tiny.
To compare, just roughly:
For roughly the same size you can get declarative/reactive rendering with React, or an optimized FP standard library with ClojureScript, or data driven visualizations with d3 (roughly 2x the size).
For a tenth of the size you can get stuff like htmx, or a json validation library (avj), or like someone said Preact (React alternative).
But for jQuery, you're paying that for basically nothing the browser APIs don't already provide. It was a godsend 10y ago, but with legacy browsers finally fading out, the last one being ie11, you really don't _need_ it anymore.
I wish we could have standardized in the Linq-like API of jQuery.
Like a collapsible section that's lightly animated.
I worry too about people not considering accessibility.
A lot of my bugs day to day is not being able to tab into things like hover menus or being able to activate buttons because someone forgot to consider correct event callbacks.
Maybe it's different now, but using a jQuery makes it more likely the code will cover cases like that.
There's some CSS transition stuff you can add to that to make it lightly animated: https://css-tricks.com/how-to-animate-the-details-element/
Yeah, jQuery might make some things easier, but when possible, using native HTML elements makes things even easier,
This isn't a complaint you can level at the gov.uk team. They're obsessed with accessibility. Gov.uk is probably the best example of a well-designed, well-built, completely accessible website on the whole internet.
const $ = document.querySelector.bind(document);It provides a clean API for manipulating the DOM, as this site demonstrates (which is ironic): https://youmightnotneedjquery.com/
Personally, for simple sites, I aim for vanilla JS but use jQuery (cash, actually) where it makes sense - such as working on collections of elements.
Steve Gibson's site is an example:
I think a lot of people owe a lot of thanks to jquery.
But in 2022 vanilla javascript is all you really need.
// jquery
$(selector).on('click', fn)
// vanilla js
document.querySelectorAll(selector).forEach(el =>
el.addEventListener('click', fn)
)Having said that, for the sake of 25kb - if you use more than a handful of features you might as well just include it.
It takes only 1 minute to write a wrapper, so you will write one, and I'll write one, and your dog will write one.
It's even easier if you copy paste from here: https://anguscroll.com/just/
your npm's dependencies authors cat will write a small wrapper and wont know about yours.
But most of the time, you find you need another wrapper, and then another, and the next thing you know you have most of jQuery, just not as uniform or as well tested.
I've seen this with database ORMs also.
document.addEventListener('click', function(e){ var t = e.target;
if(t.closest('.foo') && t.nodeName.toLowerCase() === 'button'){
e.preventDefault();
// do stuff here
}
else if(t.closest('.bar') && t.nodeName.toLowerCase() === 'a' && t.classList.contains('here')){
e.preventDefault();
// do smth else here
}
}, false);one listener to rule them all...?
elegant enough and once you get used to it...
.closest can be pollyfilled too..
At the very least there are some jQuery alternatives that are modular, smaller, and have less backwards compatibility like iirc zepto.
The point seems to be that you don't even need that any more, so just get rid of it. Not sure why people latch onto cruft so much and defend its continued use.
On the performance side they cite 10 percent improvement, which doesn't sound like much to a lot of people. But remember that performance gains/regressions get compounded. Maybe there are 8 things that each eat 10 percent - you either start improving somewhere or you just refuse to even try. If I could improve 10 percent while removing a dependency I'd be all over that.
I think this really seems to stem from a "I'm only used to jQuery, anything else is a big mental effort to learn and I'd rather stick with what I know".
I get it. Vanilla JS, if you're not used to it, is scary. But if you're advocating for jQuery "for simple interactions", and assuming it's simpler than vanilla JS, at some point you should ask yourself if you're just letting your skills stagnate, and staying stuck in the past. You owe it to yourself to update your skillset. If you decide you still need jQuery (e.g. maybe you need a plugin/library that requires jQuery), then fine. But at least you'll be making an informed decision, not a FUD-driven one.
Handcrafting JavaScript applications without jQuery is possible, the real question though is: is it convenient if you like and find productive using jQuery? Here's a fact: you can always remove jQuery later when the product is mature and standards understood and there is time budget for it.
A characteristic of communities with lots of people that do not have a theoretical background. JS, PHP, jQuery, some parts of Ruby/Python -- they defend it with their life, and I argue it's because the rest of the world looks very scary to them.
That said, I don't like how complicated modern day front-end development is, to the point where you need a university degree to even try and fathom some of React's inner workings (e.g. https://reactjs.org/blog/2019/11/06/building-great-user-expe...) etc.
I like the idea of React, just not what it has turned into. The amount of tooling that it has created to do things that should be simple (but aren't because of the runtime and/or the programmer), and the gymnastics it goes through so that people can have their precious (often unnecessary) SPAs, is ridiculous. That, and JSX continues to be an abomination that shits all over separation of concerns so that smoothbrains don't hurt themselves trying to reason over it.
https://javascript.info/custom-elements
I've been using them lately and I think they are the bees knees.
Would love for there to be One True Way(tm) without the framework question.
While it may be nice, for large production apps we'll take the filesize gains where we can find them.
That said I don't expect a massive impact from this change, but removing unused code is going in the right direction.
And then on top of each restaurant app, you also have Uber Eats, Door Dash, etc., which again, basically so the same thing.
There should really be a single fast food app, I select my restaurant, and it shows me the options (which is basically google maps with mobile websites that would actually work). There's no reason for every restaurant and delivery service to have their own app.
Now as JavaScript accumulated a lot of legacy stuff only kept for compatibility + also numerous verbally/syntactically sub-elegant APIs IMHO it is time to design a language which would simply be "better JavaScript" - clean, modern and elegant yet have no fundamental differences so it would be very easy to transpile by just string replace/mapping, essentially just a lightweight "syntactic sugar+discipline" layer. Then it can be integrated in browsers directly.
JS' problem is that it is fundamentally not "clean, modern and elegant". It was designed in a couple of days. And all the greatness that's added to it nowadays is done in a much better design process than at it's inception, yet some choices made at it's inception can never be reversed.
I've written some Elm and think it is phenomenal at being a better JS; but it fundamentally very different. Rotten fundamentals are notoriously hard to fix; especially when a lot has been built on top and needs to keep running.
I agree it's not a clean superset like TS is, but for the app I wrote I did not have to use any JS except in instantiating the app (3 lines iirc).
I have a bunch of old code that uses jQuery, it works, everything new is vanilla but otherwise it's not a big impediment / problem that I find.
SPRINKLES
Still good to remove unncessary dependencies, though.
I'm sure with some math you can make a calculation on how much bandwidth and energy was saved with this One Clever Trick.
gov.uk doesn't have many animations anyway.
Your citizens an average rate of pay of Y per year. Some of time they save by getting stuff done on a government website will be put into getting more economic work done. If the citizens do 10 billion pageviews of gov.uk per year, and you shave off 20ms, thats 27 human-years of work per year. So it is certainly worth making this optimization, even if it takes a few people a few months to figure out how to remove jquery.
A) jquery deals with inconsistent browser implementations, largely in older browsers
B) replacing it with modern API calls made the website more usable for all users including those on older machines (and presumably OS’s)
I don’t see how to square those.
The other problem you get is common to a lot of frameworks: it’s good that you can get a lot done but that means you can get s lot further without learning how it works underneath and by then you don’t want to revisit all of that code. This is especially easy to miss when your developers all use fast systems - React 3+ orders of magnitude slower isn’t noticeable on your $5k MacBook Pro but it might be when your grandfather tries to use that site on his 2011 PC, and by then you probably don’t want to do a messy refactoring on a large codebase.
No matter what the library itself provides, to use it you have to go back to working like how developers in 2014 and before used to work with JavaScript, so that's a very real consideration that the "I still like to use jQuery" folks never mention. Are they writing all of their code as pre-2015 'classic' JavasScript as well?
Some of the more contrived AJAX to update parts of a page is being replaced by HTMX, some page loads are being replaced. It is working very smoothly and at a vastly higher speed (also, incremental) than redoing everything with React, the other option tabled. I'll certainly be using it more.
$.getJSON('/my/url', function(data) {
});
or
var request = new XMLHttpRequest(); request.open('GET', '/my/url', true);
request.onload = function() { if (this.status >= 200 && this.status < 400) { // Success! var data = JSON.parse(this.response); } else { // We reached our target server, but it returned an error
}
};request.onerror = function() { // There was a connection error of some sort };
request.send();
?
$.getJSON('/my/url')
.done(data => {
// success
})
.fail((jqxhr, textStatus) => {
if (textStatus === 'timeout') {
// connection error
} else {
// HTTP status error
}
})
And also consider the Fetch API alternative: fetch('/my/url')
.then(response => {
if (!response.ok) {
// HTTP status error
}
return response.json()
})
.then(data => {
// success
})
.catch(error => {
// connection error
})Having read the vast majority of comments it seems some people think jQuery is unnecessary/obsolete. Others say it's API is better, more concise, more flexible, etc.
As a newbie I decided to learn vanilla JS as I was too confused with the state of the various frameworks; I mean what one would you choose to start with?
That said I'm interested in what jQuery can do that vanilla JS can't.
I never consciously made a decision to stop using jQuery, but after moving to frameworks like Svelte, there's just not a need for it most of the time (it's been years since I last added jQuery to a project, and I think that was only because I was using some third party lib that depended on it). YMMV of course.
But if you're starting today and want to have it easy in your career, learn React or Vue. They pay better and they look good in your CV. And I say that as someone who likes jQuery.
If you want to bet on something new, I suggest https://kit.svelte.dev or https://www.solidjs.com
jQuery is written in JS, so jQuery can't do what JS can't.
The main reason for using jQuery, as you say, is a cleaner API for DOM manipulation...
$(".something").parent().append($("<button />").text("click me").click(fn));
If you know nothing about jQuery, you can guess what that does. Of course, you can do it in vanilla JS too. However it's a little harder to write and (more importantly) read.I've done work using jQuery and several of the modern stacks and maintain much of it today. When I have to dive back into this work the jQuery stuff is usually painless. The Angular/React/etc. stuff causes an internal groan; even weeks after 'finishing' one of the latter some significant fraction of the tools and libraries are obsolete and the first thing you find yourself squandering time on is nursing it all into shape again. Years later you're also faced with either clinging to the old idioms that have been supplanted by 'better' ones or reworking a bunch of stuff. jQuery has never inflicted this problem on me.
Also, I don't really buy the "you might not need it" argument. jQuery reduces cognitive load by normalizing most of what you need to do to a vanishingly small and less error prone API. There is real value in that. jQuery delivers far more than just backfilling.
While I have a hard time imagining a client in 2022 that is so anemic that the cost of jQuery actually matters, it appears gov.uk has convinced itself that the removal of jQuery is a triumph for their use case. I've never had to deal with that use case. I doubt most people have or ever will. And so I take all of this with an appropriate grain of salt; if it's a choice between productivity and shaving a few points in blocking percentiles I'll take the former every day and twice on Sunday and the people that pay me are grateful that I do.
I learned about htmx in the comments of this discussion. I'm definitely going to give that a spin at some point. Thank you HN.
Instead, I've noticed everyone re-inventing the wheel. Take Bootstrap5, which "eliminated jquery and we wrote our own!" but now, it is much much larger. Then your next framework does the same, and so on, now we're downloading 1mb of javascript files just to display grandma's 160 byte tweet.
This "trend" has been like 5+ years in the making. And it's simply a result of jQuery becoming less necessary as core JavaScript in the browser gains features.
This is also problematic if your project has a dependency tree that needs multiple (incompatible) versions of jQuery.
jQuery made animation and such easy to do. But now we have CSS for that.
There's no value in chest pounding and proclaiming "Tool X is stupid. No one should use Tool X." Given the diversity of the internet, it's naive to believe you understand every possible use case. Just let it go already.
I would assume that the British government had considerable resources to put on the rewrite so it's quite possible that the removal was part of a general site refresh.
I see that's now removed, but Recaptcha is still there. The site works without it, but it seems a bit odd to me that by default, my data is shared by my government with a third party company when I want to participate in democracy online.
Jquery is passive, just loading jQuery in the page itself doesn't do any harm. could be some plugins they are using might be doing something unnecessary.
Now I'm curious what the CSS looks like for devs who have only ever known VDOM frameworks. Regular CSS can be pretty bad, particularly on a mature project. Are we talking dumpster fire or three ring circus here?
I used to hate code generators because the code quality was always so bad that if a midlevel or senior dev was writing code like that I'd be talking to our manager about firing them, and for a junior dev we'd be talking about more intensive mentoring or even a PIP.
Once Sass introduced SCSS, that was the first code generator I ever met that actually impressed me, and Less is very close. The default CSS out of it looked very much like the sort of CSS you would expect from a project after someone had already gone through and cleaned up all of the cliched failure modes for medium sized projects. It felt like having a fast forward button. Still one of the fastest 'sells' for me, and I do quite a lot of technology selection for projects.
Not that it's perfect. Poorly written mixins/functions can generate way more CSS per call than is necessary, and I have a team of overbooked people that I need to sell on prioritizing fixing this sort of thing and I just can't find the bandwidth because there are always 2 more pressing issues I need to talk to them about. I can't squeeze blood from stone, and I can only ask for personal favors about as frequently as I can grant them, modulo any turnover - which has become a problem. Turns out if I take a shine to you, you're also really easy to hire somewhere else.
I would give it 5 marks out of 10. It’s decent but not a bastion of good design.
Gov UK design system is poorly usable. From color use to disorganized, scattered layout; it’s put together with haste and not much thought.
What it’s good at is looking sexy and minimal which captivates a lot of people.