Native Javascript alternatives to jQuery methods
github.com
github.com
- Doesn't automatically camel-case the property name.
- Doesn't automatically vendor-prefix properties if needed.
- Doesn't support getting/setting CSS variables.
- Doesn't automatically add the `px` suffix to numeric values when appropriate.
- Doesn't fail gracefully when dealing with non-element nodes (`node.nodeType !== 1`).
IMHO there are too many details that you now have to think about when using such "native alternatives" that's not worth it. From my very unbiased opinion I think it makes more sense to just use cash, which only needs ~5kb when minified and gzipped, and can be even partially compiled to remove the stuff you don't need.
Fixed that for you. There are better ways to integrate with the DOM than jQuery nowadays. It’s not a good fit unless you’re just trying to tack on a dropdown menu onto a decade old Wordpress theme, IMO.
You will have/want to factorise these methods anyways because some of them are just ridiculously long. jQuery has already done that and at least it is very consistent.
I don't particularly understand the rush to rip jQuery out of everything. It seems like a lot of people are doing it just because it's the trending thing to do. There are some things that jQuery does very well -- even in today's world where modern web dev is dominated by SPA components.
I'm the maintainer of https://github.com/elliotnb/observable-slim and https://github.com/elliotnb/nimbly -- the latter of which is an SPA component framework whose core requires jQuery. It uses jQuery to update DOM nodes with `replaceWith`, merge deeply nested objects with `extend`, among other things. Nimbly components are not required to use jQuery -- only the framework core uses it. Aside from the eliminating the extra 69KB footprint from adding jQuery 3.1.1 slim min, I don't see any reason to rush to rip jQuery out of the Nimbly core. On the contrary, using jQuery helped us get the framework built faster and helped us keep the code expressive and easy-to-follow.
• Camel-casing the property name: I can do that myself readily enough; remember this lets you deal in direct property access, so we’re talking things like `styles.backgroundColor` rather than what would otherwise be `.css('backgroundColor')`, where using the kebab-case is nicer. (I would issue one caution: the kebab-case `float` becomes the camel-case `cssFloat` because `float` was a reserved word; this is a little like how for becomes htmlFor and class className.)
• Vendor-prefixing properties: in the library we use for FastMail, we used to have vendor prefixing; but when we dropped support for IE<11 and other ancient browsers recently I steadily whittled that down until there was only one item left, and so I decided to just special-case that one item. Vendor-prefixing is basically a thing of the past; the only one that I found to still be relevant is `user-select`.
• CSS variables: fair, but using `.setProperty('--foo', value)` and `.getPropertyValue('--foo')` is not onerous in those situations where you need to refer to a custom property.
• Adding `px` suffix to numeric values when appropriate: I don’t actually want that. I’d much prefer it to throw an error if I tried to assign a number to something that wants a dimension, but that is unfortunately not possible; yet it’s likely that any incorrect code that I write will not work, and so I’ll notice. If I really am working in pixels, I prefer to do so deliberately.
• Non-element nodes: why on earth would I want it to fail gracefully? I want it to throw an exception, because I evidently did the wrong thing. Also, if using a more strongly typed language such as TypeScript, this pretty much becomes a non-issue.
Things like $.fn.css are completely generic, taking a single object and needing to act on it—and so most of these features make sense there. But in the concrete situations where you use such functions, you can reasonably do things like call different functions, instead of just passing one object; and I think that there, most of them are instead either misfeatures or not of value any more due to better browsers and possibly TypeScript.
I like efficiency, and I like correctness; for that reason, I like the fact that the native methods don’t do most fo these things automatically. I don’t want to inefficiently do most of those things.
Sure, but now you have to think about this, which makes those functions a bit less of a replacement for jQuery.
> • Vendor-prefixing properties: in the library we use for FastMail, we used to have vendor prefixing; but when we dropped support for IE<11
> Vendor-prefixing is basically a thing of the past; the only one that I found to still be relevant is `user-select`.
I think you still have to prefix the appearance [0] property too, I would guess probably a few more as well, as I think browsers sometimes implement a vendor-prefixed property before the implementation is stable enough, so I guess if you want to use something particularly new you might need to vendor-prefix it.
My point is that with jQuery you don't have to think about all this.
> • CSS variables: fair, but using `.setProperty('--foo', value)` and `.getPropertyValue('--foo')` is not onerous in those situations where you need to refer to a custom property.
Right, but now you have to remember to use different functions. If you want to abstract this away in a separate `css` function you'll find yourself basically reimplementing what jQuery or cash does (ensuring it works, it's performant etc.), perhaps it might have been better to spend that time improving your product instead.
> • Adding `px` suffix to numeric values when appropriate: I don’t actually want that.
> • Non-element nodes: why on earth would I want it to fail gracefully? I want it to throw an exception, because I evidently did the wrong thing.
Fair enough, but that's what jQuery does, maybe you want something else, maybe not something I would call a "jQuery alternative" in this context.
> I like efficiency, and I like correctness; for that reason, I like the fact that the native methods don’t do most fo these things automatically. I don’t want to inefficiently do most of those things.
I'm pretty sure the bottleneck of your app will basically never be the check for css variables or something like that. And the time spent to reimplement all/some of these functions might be better spent improving the app instead, to me this argument feels like saying: I like efficiency, I only write my apps in C, you can absolutely do that but by the time you reach a MVP I would have probably made a much better overall and maybe even more performance JS app, since while you'd be thinking about managing memory and all that I would have surely spent more time thinking about algorithmic improvements and performance optimization in general.
[0] https://developer.mozilla.org/en-US/docs/Web/CSS/appearance
No new properties are being prefixed; that technique is dead, and the only things prefixed are so for historical reasons.
With the exception of CSS var getters/setters (for which there are distinct getters/setters), all of your points champion things being done "automatically", by "magic", "loosely", rather than being strict.
To reword:
- Doesn't arbitrarily transform property names - Doesn't add extranous properties - Doesn't magically convert integers to strings - Doesn't silently hide logic errors on invalid nodeTypes
This comes down to an essential philosophical difference, whereby the jQuery APIs favours automatic value transformations so devs don't need to understand the specific types of values being passed.
> - Doesn't arbitrarily transform property names
Ok, would you then prefer to reimplement the vendor-prefixing logic on your own or just not support browsers that only support the vendor-prefixed version of a property?
I can see your point, and in some ways I agree with that "philosophy", but my point was that I wouldn't personally call these functions "jQuery alternative" in this context, as the 2 are pretty different beasts.
The fact that `classList.add` has a different interface to `$.fn.addClass` isn't really a big deal—this would be the case with most migrations from one API to another without matching interfaces. The question is of internal functionality—the only thing jQuery "adds" here is being lenient about the param type accepted.
https://github.com/nefe/You-Dont-Need-jQuery#2.1
I don't want to have to figure out that there is a "known bug and will return 'auto' if style value is 'auto'". jQuery takes care of that crap for me.
Say what you want about jQuery, but it just works.
The jQuery examples are always cleaner, shorter, more intuitive.
I think I'll always be prototyping in Jquery.
Large stuff we built in React, Redux etc... But if you need a quick tool or prototype, just adding a single <script> tag to get JQuery from a CDN and you're ready to go. Nothing is going to beat that, right?
If I have to do any DOM manipulation outside of perhaps hiding or showing an element based on a button press, I typically find it far more unwieldy to do all that stuff with jQuery than just scaffolding out a quick Vue component.
Plus, there is a build available with a runtime template compiler, so you can just pull that in via a CDN and prototype without needing a build step.
Obviously, it varies a lot based on the sort of things you build, but I’ve found it to have sped up my prototyping process enormously.
I like Vue, never really jumped into react, but I hate using npm and all of the javascript build tools.. I end up fighting with them for a while and decide it's back to jQuery and simplicity. Always works.
I didn’t (and still don’t) know any of the $cool_kids front end frameworks. But it couldn’t have been a SPA anyway. Each of the pages were created by a CMS that ran on the web and in a native mobile app that had to be able to work offline.
However if you're writing a 10 line script that does something really small (eg. if you have a static webpage and need to make one button slightly interactive) then these guides tell you how to do it without importing all of jQuery.
(Maybe they should put some of its functionality into the JaveScript standard?)
Instead, you now put money and time in building a wheel for very little benefit (if you can feel the performance of jQuery, you're doing to much DOM operations and you probably wouldn't benefit much from stripping it out).
Some projects are not meant to last long-term, and jQuery would work just fine. Even if it is old fashioned.
Can you elaborate on the runtime overhead issue? If you write your own JS functions to replace jQuery, you’re still adding runtime overhead... and jQuery likely wrote a more efficient implementation to begin with; jQuery is battle tested and one of the most widely used pieces of software in history, what makes you think your code will have less runtime overhead?
Have you ever measured this on a large scale? I’ve never found it to be true because there are many CDNs, versions, and browser caches are not infinite. If performance is a priority it’s almost always faster to serve it directly to avoid things like the DNS and TLS latency from those CDN connections.
All this talk of trying to skim off a few kb of load time only applies to extreme edge cases of landing pages with flighty potential customers.
And your suggestion is write your own custom wrappers to avoid overhead? So you or someone else can learn all your custom things.
No to all of that. Get off the "too cool for Dad" train and just use jQuery if you already know it and it fits for what you are doing. If something else is better, (including native), use that.
Also, jQuery is self-contained, doesn't shove numerous other packages into node_modules.
Totally a bonus. Had to deal with npm audit and it warned about breaking changes and security problems. So I did npm audit --force. npm had a "I sure hope you know what you are doing" message. That's not very comforting >___>.
jQuery is a utility that abstract/hides away all the hideousness that is JavaScript and its prototypes-based nature. And it does its jobs well, plus it has universal support.
Above all -- "work smarter, not harder".
Really makes you think the DOM is needlessly complex and verbose.
I feel like a cargo programmer because I’ve been using jQuery for 8 years, I have learnt the vanilla JS methods, and it seems jQuery is falling out of fashion. Is it a mistake, or is still popular enough that I will be able to use it with every employer?