196 points · by thunderbong · 2y ago · 173 comments
dqs = document.querySelector.bind(document);
dqsA = document.querySelectorAll.bind(document);
So instead of country = document.querySelector('#country');
cities = document.querySelectorAll('.city');
I can write country = dqs('#country');
cities = dqsA('.city');
For everything else, I am fine with just using the native browser functions.I usually import the two functions from a module like this:
import { dqs, dqsA } from '/lib/js/dqs.js';
This is the module:
Sounds useful and reasonable.
> I usually import the two functions from a module like this: > > import { dqs, dqsA } from '/lib/js/dqs.js';
Utterly absurd. Just copy and paste. It’s only two simple lines, how could it be worth a dependency?
Of course you are supposed to master which of the es/interop/amd/require incantation you are supposed to use. I wish Typescript would have mandated one style and one style of JS module only!!
And I’ve never succeeded to find a good guidelines on which kind of JS module I should use. Any advice on what is a very easy and stable and worth-to-learn technique to master imports in 2024?
Maybe you'll never write enough JavaScript to have additional utility functions. You'll probably never need to modify those two lines. But copying and pasting like that makes for quite the code smell. Because if you're copying and pasting that, the question that someone may never actually verbalize to you is what else in the code is copy and pasting instead of being turned into a shared function in a libray?
On the other hand, with bundling though it’s totally fine to have a module just for these two helpers. (Even better if it can be inlined, but I haven’t seen anything supporting this since Prepack, which is still POC I think.)
dqsA = s => Array.from(document.querySelectorAll(s));
Reason why I do that very often is because it allows all array methods to be used on the result, like .map() or .filter(), which makes it feel very much like jQuery. YMMVI wonder what I would have to look for in my codebase in terms of what could break when dqsA starts returning an array instead of a NodeList?
NodeList.prototype.__proto__ = Array.prototype;
Problem solved without Array.from().This is JavaScript though…
https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputEl...
FYI: I know you meant to give an example, but element tags with ID are DOM variables as well.
...I just checked and it turns out I first blogged[0] about it 12 years ago. Time flies.
[0] https://nmn.gl/blog/javascript-shortcut-for-getelementbyid-a...
The css to do that comes from the Normalize-OpenType.css [0] library
[0] https://kennethormandy.com/journal/normalize-opentype-css/
The main problem I have with the implementation is that it chooses to fail silently when the list is empty. I’ve fixed too many bugs of this sort, often caused by someone refactoring a DOM tree to do some fancy layout trick after the fact. If I were implementing jquery again today, I’d make it error on empty set by default and add a call chain or flag to fail silently when you really don’t care. I’ve spent a few hours poking around at jQuery seeing what it would take to pull out sizzle and do this, but never took things any farther than that.
At the end of the day jquery is about the old debate of libraries versus frameworks. We’ve been doing SPAs with giant frameworks long enough now for the Trough of Disillusionment to be just around the corner again.
It's possible it's also situationally useful to say "if there aren't any document elements that match this selector, error out, if so do this with all of them." I'm struggling to imagine a specific situation in which that has compelling advantages (and would be interested in elaboration), but let's say it exists. Then something like this:
$.fn.mustMatch = function(onNoMatch) {
if (!this.length) {
if(typeof onNoMatch == 'function') onNoMatch(this);
else throw "mustMatch failed on selector " + this.selector;
}
return this;
}
would make it easy to explicitly add the guard condition with an invocation like `$("#selector .nonextant").mustMatch().each(function (emt) { /*do this*/ })`, rather than having it invisibly ride along with every comprehension and making the "whether there are any or not" case harder.And if for some reason one were possessed of the conviction that implicit enforcement of this universally within their project outweighed the advantages of explicit options for both ways, it'd probably be better to patch the jQuery lib for that specific project than enforce it as a standard for everyone worldwide.
As I said above, you’d want a way to override the behavior in the few cases where it’s inappropriate
if (!!foo) { //do thing }
document.querySelectorAll('input[type=checkbox]').forEach((i) => i.checked = false);
This takes advantage of iterable NodeList and iterator helpers.Many parent queries can be done with element.closest()
I think it is possible to replace the jQuery init function with your own implementation that enforces length.
<html>
<head>
<script src="https://code.jquery.com/jquery-4.0.0-beta.2.js"></script>
</head>
<body>
<ul id="list">
<li>foo</li>
<li>bar</li>
<li>gnord</li>
</ul>
<script>
(function ($) {
"use strict";
if ("development") {
// jQuery strict mode, logs errors on empty selectors if not opting out
const getStackTrace = function (error) {
const stack = error.stack || '';
return stack
.split('\n')
.map(function (line) {
return line.trim();
})
.filter(function (line) {
return !!line;
});
};
// by calling try() we silence selectors that returns empty
// problem is that this function runs after the selector
$.fn.try = function () {
this.__store.try = true;
return this;
};
// thus we use the GC to check when the jQuery object is destroyed
const registry = new FinalizationRegistry((store) => {
if (!store.try) {
console.error(
'Empty result for selector "' + store.selector + '"',
getStackTrace(store.error)
);
}
});
// override the init method
const jQueryInit = $.fn.init;
$.fn.init = function (selector, context) {
const result = new jQueryInit(selector, context);
if (selector && result.length === 0) {
const store = {selector: selector, try: false, error: new Error()};
result.__store = store;
registry.register(result, store);
}
return result;
};
} else {
$.fn.try = function () {
return this;
};
}
})(jQuery);
// normal usage, have result, no error
$("#list li").each(function (i, el) {
console.log(el);
});
// empty result, triggers error log
$("#nolist li").each(function (i, el) {
console.log(el);
});
// empty result but with try, no error
$("#trylist li").try().each(function (i, el) {
console.log(el);
});
</script>
</body>
</html>Lightweight development for lightweight applications is a bit of an oxymoron at this time.
Apt description
About the only place I could see a benefit from this library is maybe in embedded, where space really is an issue. I've created a few IoT devices with web interfaces that are built-into the tiny ROM of the device. A 6KB library is nice, but I'm using Preact with everything gzipped in one single .html file and my very complex web app hosted in the IoT device is about 50KB total size gzipped - including code, content, SVG images and everything, so jQuery or a JQ substitute isn't going to be a better solution for me, but maybe it fits for someone that doesn't know how to set up the tooling for a react/preact app.
Meh for most places I've worked though.
B. Your two examples provide different things. This is like saying it's OK to include any old multi-megabyte dependency if a site loads a couple mb worth of images. There's no reason to stop considering the size of the small parts just because you decided you need some large parts. Things add up - that will never stop being a useful thing to remember, in any context.
But I guess you're really asking why the developer would spend time on rewriting a library. Is that really surprising? Most of programming is rewriting something that's been made before, either because you have to for your job, or because you need it to do something slightly different, or have different performance characteristics, or just want to learn how it's done.
The era of jQuery and it's clones are over. People need to move on. If you're ever at the architecture level of your code base and think "What package should I use for DOM manipulation?", you're doing something wrong.
My current client has a web application written in a lightweight strongly typed php framework, htmx and sprinkled jquery.
Devs move very quickly, the website is blazing fast, and it makes around 140k mrr. It's not small. About 350 database tables and 200 crud pages. Business logic is well unit tested.
You don't need to make jQuery the center of DOM manipulation if your application swaps dom with htmx with all the safety and comfort of a cozy backend.
It feels magical. And the node_modules folder is smol. Icing on the cake.
I look forward to jQuery 4 and 5.
You don't see this kind of architecture in CVs because these people are too busy making money to bother.
* Animations, tweens, timelines use pure CSS, instead of jQuery's custom system.
* Use one element or lists transparently.
* Inline <script> Locality of Behavior. No more inventing unique "one time" names.
* Vanilla first. Zero dependencies. 1 file. Under 340 lines.
https://github.com/gnat/surreal me() is guaranteed to return 1 element (or first found, or null).
any() is guaranteed to return an array (or empty array).
Array methods
any('button')?.forEach(...)
any('button')?.map(...)
So does any() always return an array as described near the top, or can it return null as implied by the example below?Locality of Behaviour is of special interest to me.
How is your experience with currentScript.parentElement?
Last month I did a quick research and my impression is that it wasn't reliable in some probably niche case but I can't remember when.
But I didn't investigate much and I'm glad you made it work!
If I load 3 consecutive scripts currentScript.parentElement should still work in all browsers right? As long as it is not async or module, which is fine with me.
SvelteKit had this conversation and they ended up implementing random ids for elements to set their targets:
https://github.com/fabiospampinato/cash/blob/master/docs/mig...
export type inferSelectorElementName<sel extends selector> =
| string extends sel ? HTMLElement
: sel extends `${infer A},${infer B}` ? inferSelectorElementName<A | B>
: sel extends `${infer A}${'.' | '[' | '#'}${infer _}` ? inferSelectorElementName<A>
: sel
export type inferElementFromSelector<sel extends selector> =
| string extends sel ? HTMLElement
: inferSelectorElementName<sel> extends infer S ?
S extends '' ? HTMLElement
: S extends keyof HTMLElementTagNameMap ? HTMLElementTagNameMap[S]
: never
: never
TS types may go quite deep
Check Arktype library [https://arktype.io/], it's type definitions are basically a Typescript written in JSON const user = type({
name: "string",
platform: "'android' | 'ios'",
"version?": "number | string"
})- A SQL database implemented purely in TypeScript type system (https://github.com/codemix/ts-sql)
- Chess implemented entirely in TypeScript (and Rust) type systems (https://github.com/Dragon-Hatcher/type-system-chess)
- Lambda calculus in TypeScript type system (https://ayazhafiz.com/articles/21/typescript-type-system-lam...)
[1]: https://github.com/aleclarson/dough
P.S. If you can cope with jQuery in a medium/large app, good for you. But it's not my cup of tea.
It looks like cash has that as well, just bit more hidden in the documentation https://github.com/fabiospampinato/cash/blob/master/docs/par... If I'd use it I'd give that a try.
Somehow I still think going with what the browsers have to offer nowadays is a better option - actually it's really good and jQuery isn't really needed anymore. Especially when even the small jQuery alternative is still 6kB, while Preact, a react like lib, is only half the size.
Reminds me of this old joke: "Why do greedy developers all learn PHP? Because there's a lot of dollars in that."
Still not sure it really is a good name for a lib: someone who doesn't already know it will probably not think about jQuery when they see this name in a dependency list...
In practice, I always need to import some huge a* library that make gains from these small alternatives miniscule.
Framework -> 50KB
Tiny version of framework -> 5KB
Lib I need and can't replace -> 1MB
Fetch will reject your GET if it contains a body (a deliberate maintainer decision), even though it's entirely permissible by HTTP and done by many real-world AJAX APIs. Real AJAX will do what it's supposed to. (The HTTP 1.1 2014 Spec says that including a request body in a GET "might cause some implementations to reject the request." Guess which one!)
Also, advanced features like progress are completely absent from Fetch as well.
However, there are some fantastic libraries like Axios[1], SuperAgent (requires npm), and, yes, jQuery[2], that have really excellent API's (far superior to Fetch), or you could just write your own (or use an LLM) short wrapper around modern AJAX and call it a day. h/t to Claude:
const xhr = ['GET','POST','PUT','PATCH','DELETE'].reduce((x,m) => (x[m.toLowerCase()] =
(u,d,opt={}) => new Promise((r,j) => {
const q = new XMLHttpRequest();
q.open(m,u);
q.responseType = opt.responseType || '';
if(opt.headers) Object.entries(opt.headers).forEach(([k,v]) => q.setRequestHeader(k,v));
if(opt.signal) opt.signal.addEventListener('abort', () => q.abort());
q.withCredentials = opt.credentials === 'include';
q.onload = () => r({
ok: q.status >= 200 && q.status < 300,
status: q.status,
headers: new Headers(q.getAllResponseHeaders()),
text: () => Promise.resolve(q.responseText),
json: () => Promise.resolve(JSON.parse(q.responseText)),
blob: () => Promise.resolve(new Blob([q.response])),
response: q
});
q.onerror = () => j(new TypeError('Network request failed'));
q.send(d instanceof FormData ? d : JSON.stringify(d));
}), x), {});
This gives you xhr methods with a fetch-style API and you can still do all the things that fetch can't (but this won't do real streaming or cache control like Fetch, but it'll do 95% of all common use cases in a tiny bit of code.)Each method listed above returns a Promise that resolves with the XMLHttpRequest object or rejects with the error. So you get both the Promise functionality and full access to the XHR object in the resolution.
Usage:
xhr.post('/api', { data: 123 }, {
headers: { 'Content-Type': 'application/json' },
credentials: 'include',
signal: abortController.signal
})
.then(res => res.json())
.then(data => console.log(data));
For more advanced AJAX stuff, check out the very powerful and flexible Axios library[1].And, if you don't need AJAX but do want some of the features from jQuery (like some of the more unusual selectors) that aren't in Cash (to save bytes!), AJAX (and special effects) is excluded from jQuery Slim which brings the code down to only 69KB[3].
1. Axios https://github.com/axios/axios (41kb)
2. jQuery AJAX https://api.jquery.com/jQuery.ajax/ (87kb but includes ALL of jquery!)
Thanks for your continued work on it!
Looks like it does a great job of dealing with tables on mobile, putting my own manual efforts for that task to shame. I would typically just enable horizontal scrolling on mobile and call it a day. Now I feel a bit guilty about that after seeing the much better ways datatables does it!
I used the same basic signature for the `$()` function. However I found that 95% of the time I don't need to use the chain method on a collection. There's almost no scenario in which I want to do <collection>.addClass() etc. There's practically ZERO situations in which I would use something like attach an event to a collection of nodes, since event delegation is more elegant (attach a single event and check for event.type and event.target).
So TLDR I made $() always select a single element with `querySelector()`, which means I could remove the collection/loop from every chained method like addClass() or css() or toggle().
Point unless you write bad code to begin with, you can probably make this significantly smaller by removing the collection handling. The 1% of the time it is warranted to do an addClass() or something else on a bunch of nodes you can just go native and if the collection is small enough just call $() on each element.
PS: I guess the subtext also to my post is sometimes something looks logically elegant, like the ability for any chained method to act on the collection selected by $(), but it may not make any sense in the real world.
a lot of apps -- just need a few reactive interactions which htmx, alpine and cash or other libraries like hyperscript, stimulusjs etc fulfill. I mean your standard line of the business apps. consumer apps it might be different, but then even those that have use once mechanics such as Kashi, polymarket, reddit etc don't need to use react.
Only tiny ones, I don't remember the details now, IE11 ended up providing almost all the same APIs.
a jquery alternative
actually the native typescript is interesting
The manipulation should be on the backing state, and then the dom should just derive from that, such as with data binding.
But I think the OP's jQuery replacement is also dropping features in the service of a small footprint. So this was my 80/20 contribution to the "smallest jQuery replacement" problem ;)