A summary of jQuery method alternatives in native browser implementation
github.com
github.com
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.
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>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?
- "finding ways to perform better" by living without it is not something that happens in real life. To the contrary, living without adequate financial support has been shown by many studies to lead to anxiety, mental issues and general under-performance.
- It's clearly an unnecessary and disingenuous attempt to bring a loaded political agenda of your own into an otherwise innocuous discussion of programming libraries.
I can say this with clarity and objectivity because I have had to rely on government handouts a long time ago when I had my first kiddo while being an unemployed college student only to drop out of school and work below the poverty line. Some people can figure it out and others cannot. The embarrassment and offense are very much a part of that issue as well as the imposter syndrome that is so obvious in so many developers.
A comment is made that correlates a popular technology opinion to a dreadful political subject. Offense ensues. Next... sadness.
A couple of months ago I heard the most perfect description for such a sentiment from an army colonel to which he described such (in a broader context) as fragility. Sadness is not a valid qualifier for making a rational qualification of competencies... except in software where imposter syndrome is rampant.
I will stop here. I have had this conversation numerous times in the past and for people who suffer from fragility it is generally not understandable beyond an honest disclosure of what it really is. To me welfare is the perfect analogy. For people addicted to that system no rational conversation will convince them double the work in the short term could have 10x benefits later down the road. They can't see it and don't want it. They are content and utterly reliant upon the tools provided to them.
Big deal.
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.
Satellite in a bit of a red herring in terms of the point I wanted to convey.
I also spent about 3 years working on systems that had to work across satellite connections so I have a little bias as well :)
jQuery is also not doing a whole lot on startup, its functions get called when needed. Lodash is the same.
[1] http://httparchive.org/compare.php?&r1=Nov%2015%202010&s1=Al...
2.5MB is absolutely ridiculous. Regardless, you just created a straw-man. jQuery is, what, 26kb minified + gzipped? So you could also say that if website is 100kb then jQuery is 25% the size of your website.
Now 26kb is not much at all but small things add up very quickly. If you're not using it, don't include it. If you can write a tiny bit of extra code to avoid a dependency that isn't highly specialized (e.g. moment.js) it's usually a good idea on the web.
> If that means that some random satellite user has to wait 101s instead of 100
FYI satellite connection issues are more about latency than bandwidth. Adding an extra connection (if it's not concatenated) to fetch jQuery can easily add more than 1 second even though it's only 26kb. Also, I sure hope your app doesn't take 100 seconds to start-up :)
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.
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?
https://jsfiddle.net/hbLebx2d/1/
Try quickly clicking the "Toggle" button too.
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.
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()`!
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
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).The closest I can come is that, while the latter two examples are indeed more verbose, they're not really unattractive in their own right, and they do have the virtue of explicitude which jQuery's set operations, while conceptually clean and syntactically concise, lack. If you're not closely familiar with jQuery - which I no longer am, having touched it barely at all for better than half a decade now - what comes back from
$('div').prev()
isn't obvious. It probably requires experimentation in the console or a documentation review to be clear on the return value - and jQuery's documentation is, to be charitable, not of the most lucid.Meanwhile, in either of the native ES examples, it is immediately clear what's going on, albeit at the cost of additional verbosity: you're getting a set of elements, mapping each to its prior sibling, and filtering out those whose lack of a prior sibling resulted in a meaningless value in the map. (To this point, in ES5, I would instead write .filter(function(e) { return e !== null; }); the Boolean constructor is a useful shorthand, but shares the jQuery property of lacking lucidity.)
In a team with deep enough experience of jQuery that the meaning of your first example would be clear to anyone working on the code, I wouldn't object to writing it that way. In any other context, and especially on a team with widely varying levels of skill and experience not just with jQuery but with relevant concepts in general, I would strongly favor the more verbose examples, both because they're easier to follow from scratch in their own right, and because they serve as complete examples of a pattern with applications far beyond the realm of DOM manipulation and thus have value beyond there mere convenience to type.
Horses for courses, I suppose.
How horrifying.
...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.