50 points · by Liriel · 9y ago · 75 comments
With JQuery and the cookies plugin its would probably have been something like 30 lines. Thats 10 times the code you have to write, debug and maintain.
So, of course, you don't NEED JQuery just like you don't NEED any means of transportation, you can walk everywhere after all. The question is, if you want to spend you whole life walking/writing verbose ugly JS code.
However, when you're opening a comment with "Hell yeah, you do", I really have to respond.
Hell no, you don't. If you're writing 318 lines of code just to do a cookie warning, that's fine. But please don't preach that it's necessary before actually learning some javascript.
I'm also a bit baffled that it would take an entire 30 lines while using jQuery AND a cookie plugin. What are you doing to these cookies messages???
::EDIT::
I have no idea if the code below works, and it could do with a lot of improvement (thinking about secure cookies, cookie paths, or even just using localStorage instead), but I can't imagine a bit of testing and revision of the code would balloon it to even twice its size. Least of all 30 times its size.
(function() {
var cookiesMessage = document.getElementById('cookies-message-wrap');
var cookiesAccept = document.getElementById('cookies-accept-button');
var checkCookies = function () {
cookiesMessage.setAttribute('class', document.cookie.indexOf('cookiesaccepted=1')===-1?'':'accepted');
}
cookiesAccept .addEventListener('click', function() {
document.cookie = 'cookiesaccepted=1;expires=Tue, 19 Jan 2038 03:14:07 GMT;path=/';
checkCookies();
});
})();
What am I missing?But the functionality looks good! I mean, document.cookie can be a huge pain to deal with if you actually have to deal with it, and jQuery has a plugin for that - but this doesn't take any kind of parsing, just a cheap substring check, and the class list manipulation is equally trivial. Even animation could be handled in CSS.
Perhaps OP's use case is much more complex than it sounds, in a way that's far from obvious?
https://github.com/js-cookie/js-cookie/blob/master/src/js.co...
is under 165 lines with comments and provides a nice API on top .
<script src="https://unpkg.com/cookiesjs@1"></script>Big deal.
I think a better sentiment is that you probably don't need jQuery. jQuery is a great library, but with the modern state of JS, you can probably get by without it and spend that 32kb on something else more useful.
You can get Preact, RxJS-lite and Immutable in total for about 40kb - is that going to be a better use of your performance budget?
1. Your visitor must have visited other sites using jQuery from a CDN.
2. One of those sites must have used the same CDN you're using.
3. The site must have used the exact same version you're using.
4. Depending on the CDN, the version must have been served from the same URL (e.g. a problem when CDNs allow specifying partial version numbers and sites differ between referencing the full version number or just a part of it, 1.8 vs 1.8.2).
And you're already doing things right, using HTTP/2 and everything, but your client hasn't visited a site before that uses your CDN and your version via your URL, now what? Your visitor's browser has to make another DNS lookup, open another connection to a different server, possible block your own scripts from executing because they depend on jQuery, and so forth.
But if you're doing it right and using HTTP/2 and everything and hosting jQuery yourself (or possibly even use a vendor bundle) there won't be any visitors who have already got your jQuery version cached but the browser can avoid the overhead of another DNS lookup and another connection and just tell the server to send jQuery along with everything else over the same socket.
Public CDNs have been of questionable value from the start[0] but with HTTP/2 this "if you're doing it right, you're loading your dependencies from a public CDN" meme needs to finally die.
[0]: AFAIK the argument that public CDNs are a performance gain for third-party dependencies (vs bundling and/or hosting them yourself) was never substantiated with any real-world data. I guess for jQuery things have improved a bit with jQuery providing an official CDN as the default option but this doesn't help with jQuery plugins or anything other than jQuery itself.
But on the other hand jQuery unlike MVC/virtualdom frameworks loads asynchronously and adds behaviour to static html ie it's non blocking.
- Each file downloaded adds latency. This especially hurts if you're on a satellite or similar, highly latent connection. The more files you have to download the worse start-up and various loading timing can get.
- Okay, so let's say you minified and combined everything to help avoid the first issue, now you have a new issue: all JavaScript needs to get executed when included. So adding 20kb worth of JavaScript, while not all of it is executed immediately, a chunk of it is. This adds to start-up time.
- Don't forget JavaScript execution, when compared to a desktop, is absolutely abysmal. For mobile web browsers you need to shave as much time off of start-up and ready states as possible.
It claims that because there is direct access to all the DOM API, you really don't need jQuery, but then it gives examples on how simple jQuery calls maps to different, multimethod calls to the DOM API. Those examples show how jQuery provide a nice abstraction on top of the DOM.
This article is like saying, we don't need high-level languages because we can all learn assembler.
Half of the native solutions have bugs or no IE support. All are three or more times more tendious than jQuery.
The adage in the other comments seem "but jQuery is a big dependency."
Did we already forget the left_pad npm debacle? jQuery didn't break then.
If you're doing one of them, just write it out and move on. Don't pull in a multi-kilobyte dependency for one thing that takes two minutes to write.
What relevance has left-pad here?
jQuery is a convenient abstraction on more verbose DOM APIs. Using it makes development quicker and easier. Here is an educational article demonstrating what those DOM APIs look like to many who may have opted to take the quicker & easier route of learning jQuery without learning DOM.
https://jsfiddle.net/hbLebx2d/1/
Try quickly clicking the "Toggle" button too.
I don't see anything wrong with that. No one is saying that JQuery sucks or that it should die, I think the point is more "use the best tool for the job".
You can buy a massive wrench with all kinds of adjustable settings and addons and stuff but if all you ever need is an Alan key, then maybe the little one that comes with your IKEA furniture is actually better and easier to use than that massive wrench.
1. Less dependencies for your JavaScripts
2. Less "magic" behind the scenes
3. Native JS-engine optimisation
4. Switch of though-process ( jQuery, although quite flexible ), makes you think that everything is "string", "array", "object" and sometimes you need the bare Node-element e.g. https://developer.mozilla.org/en-US/docs/Web/API/Element
However, jQuery is still quite useful and I include it in most projects. It makes various tasks, like event handling, AJAX requests and minor DOM tweaks, quite a bit nicer. Zepto is a good alternative with an almost-compatible API (http://zeptojs.com). I would rather generally that developers used these off-the-shelf tools instead of implementing possibly buggy versions of functions like `height()`!
Which is significantly less convenient and readable than using set-operatic traversal and manipulation functions:
$('div').prev()
will give me the preceding sibling of every div in the page, in native, best case scenario using ES2015 arrow functions and Array.from it's something like this: Array.from(document.querySelectorAll('div'))
.map(e => e.previousElementSibling)
.filter(e => e)
and if you need pre-2015 compat you get this ball of itchy yarn: Array.prototype.slice.call(document.querySelectorAll('div'))
.map(function (e) { return e.previousElementSibling; })
.filter(Boolean)
jQuery works on and manipulates node sets, and I find that to be a beautiful and convenient abstraction. I expect that is not unlike the satisfaction users of APL or its descendants feel (although I can't for the life of me get beyond their sigil soup).While true it's important to remember this creates a new, shallow array copy. It's not something you'd want to call often.
Also it may be better to use Array.prototype.slice.call instead to avoid the extra, empty array instance your shortcut creates. How much better is likely insignificant, however; it's mostly a personal preference of mine :)
> I don't know why that method doesn't just return an array to begin with, but this is how you get one from it.
I believe this answers that pretty well (I've had the same, frustrating question in the past): http://stackoverflow.com/a/2601582/242023
...except in defining a directive.
10y after release, jQuery is an established pseudo-standard that is not going away any time soon. Even with querySelector/querySelectorAll/getElementsByTagName/getElementsByClassName, I am still using jQ as the vanillaJs API feels so clunky and verbose.
// jQuery
$el.siblings();
// Native
Array.prototype.filter.call(el.parentNode.children, (child) =>
child !== el
);
Yes, much clearer Array.from(el.parentNode.children).filter(
(child) => child != el
)
But yes, it's not quite as sexy as siblings().For example, there are new native language features in ES6 that make little utility functions like $.inArray obsolete.
If you miss the $ function for DOM element selection, it's pretty trivial to wrap querySelectorAll in your own one-line helper function.
Source: lamenting the fact that I haven't used querySelector in almost a year.
It wasn't until I resolved to try to learn JavaScript without jQuery at all that that mental barrier preventing me from understanding was removed. I blame the abstraction level and omnipresence of jQuery for preventing me from being able to learn JavaScript.
Now Ive been writing vanilla JS for a couple of years, a, learning s lot, and I gain a lot of knowledge from posts like this, Ditching jQuery, and YouMightNotNeedJquery, not because I knew the jQuery way—just because they lay out the simple JS way to do common things.
Long story short, after starting to learn JS I still cant figure out what a block of jQuery code is doing unless i re-implement it as vanilla to check and see if my guess is correct. I cant wait for the day when people are content with browser APIs for these things, many are simple but much more flexible.
When on a team it is good to use a common library that is tested across all browsers and does native calls encapsulated within it. When working on an app the last thing you usually want to get caught up on is browser inconsistencies that are easily avoidable, wasting time on that when not necessarily needed for that project. Other times you might need to go off-roading. If you always offroad though because you just hate automatic, well you won't be drinking coffee or using your phone much, you'll be worrying about shifting.
Still including a 200+kb file for jQuery... to just use well these are the most common ones I use:
var targ = $("#targ"); targ.show,.hide,.val(),.text(),.css,.post(),.done,.promise(),.each(),.remove(),.on('blur" or .on({ blur: mouseup, .height(), .width(), .scrollTop(), etc...
Probably much more, yeah certainly shorter code, gotten used to using it.
edit: At this time I always build with jQuery, always include it in the <head> section. Could wait if it's a potential thing to slow down loading of site but I usually just have a copy on my server.
jQuery by itself is something which is just nice to know is there, for quick DOM manipulation in the standard way you know how, and other devs know how. Hassle-free and accessible.
As a jQuery fan I'm glad there's more tools and methods out there, however. I'm keen on VueJS myself but not yet confident. I'll be avoiding React and Angular because to me they feel like using an industrial lathe when all you need is a Dremel.
Performance crumbling is still more likely to be caused not by choice of JS library, but shoving too much content down the throat of users because you as developer couldn't say no, or when you advised against it were ignored.
https://superdom.site/
It's probably not for anyone to use it, but it was really fun exploring other possible APIs as alternatives to jQuery and with modern ES6+If it is a simple 3-4 page website I write it in plain JS , if it is a complex website with lots of views and components I write in Vue + plain JS (if req).
But, it's nice to make something dependency-free if you can.