9 ms·
Cash: A small jQuery alternative for modern browsers
- BiteCode_dev 2y agoNote that it's really dom centric and doesn't include ajax.
- ceejayoz 2y agoIsn’t AJAX fairly well supported via fetch now?
- jitl 2y agoYeah at this point I’ve totally forgotten $.ajax API but fetch is pretty easy, just a single function call
- amelius 2y agoNow we only need something that makes websockets more resilient against network errors and corporate firewalls.
- BiteCode_dev 2y agoIn the same way selectors and map replace jquery. It depends how much sugar you want.
- _hyn3 2y ago... unless you want to send a body with your HTTP GET. There is tons of utility value in this! For example, let's say you want to GET some data but also provide some client request statistics along with the request -- happens all the time in the real world. 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 https://github.com/axios/axios (41kb) 2. jQuery AJAX https://api.jquery.com/jQuery.ajax/ https://api.jquery.com/jQuery.ajax/ (87kb but includes ALL of jquery!) 3. https://code.jquery.com/jquery-3.7.1.slim.min.js https://code.jquery.com/jquery-3.7.1.slim.min.js
- erik_seaberg 2y agoCaching is the most important reason to consider GET for a non-hypertext API. Vary headers tell the server which header diffs should cause cache misses, but there's no way to do that for an encoded body.
- jdlshore 2y agoI believe providing a body with GET is non-standard, which could lead to problems with proxies. IETF is introducing the QUERY method to fill this gap.
- _hyn3 2y agoIt's not non-standard; it's actually in the standard: https://www.rfc-editor.org/rfc/rfc7231#page-24 https://www.rfc-editor.org/rfc/rfc7231#page-24 In standard HTTP/1.1, any method can have a request body. In Representational State Transfer (REST) as defined by Dr. Fielding, HTTP doesn't even come up, let alone "methods" per se, so there is no distinction between DELETE, POST, or GET from a REST standpoint, only within HTTP as an engine for hypertext. Further, in HTTP, any of these requests can contain a request body. But, because of this behavior by the WhatWG for Fetch, the IETF has added this paragraph to the specification for HTTP/1.1: "A payload within a GET request message has no defined semantics; sending a payload body on a GET request might cause some existing implementations to reject the request." "Some existing implementations" really just means fetch. The p*ing contest between two groups resulted in a neutered and prescriptive fetch. In other words, it's fetch that is non-standard, and the actual HTTP standard had to be updated to let you know that.
- chrismorgan 2y agoYou've got the chronology and causality wrong. The Fetch API came after the RFC 7230 advice. Due to arguably dubious interpretation of arguably poor wording in RFC 2616 (from 1999) that suggested you SHOULD ignore GET bodies, various caching and proxy servers would ignore or reject GET request bodies, so that it became dangerous to use them. Since then, each iteration of the HTTP specs has strengthened the advice. The most recent 9110 family says you SHOULD NOT use GET request bodies unless you have confirmed in some way that they'll work, because otherwise you can't trust they'll work. Fetch was going along with this consensus, not causing the problem. The pool was muddied; nay, poisoned. And so the solution is the QUERY method. That's how things tend to work in such a space. See also 307 because of 302 being misimplemented.
- yieldcrv 2y agoah that’s what people were looking for a jquery alternative actually the native typescript is interesting
- xg15 2y agowindow.$ = document.querySelectorAll
- dsego 2y agoBut it doesn't do chaining and you have to loop through elements to do anything with them.
- Spivak 2y agoI'm always surprised that an API that is defined by matching 0-n dom elements doesn't return a container that by default maps over them list monad style.
- freeone3000 2y agoThere’s a fairly small polyfill that makes a DOMNodeList have the same functions as Array.
- jasonjayr 2y agoAre the various browser JS implementations clever enough not to make a new Object for Array.from(DOMNodeList) ?
- pwdisswordfishz 2y agoUncaught TypeError: 'querySelectorAll' called on an object that does not implement interface Document.
- badlibrarian 2y ago[flagged]
- lofaszvanitt 2y agoThis perfectly shows why native js is ridiculously shittified. el.getBoundingClientRect().height; gtfo
- deleted 2y ago[deleted]
- lelanthran 2y ago> I thought we got past this. > > https://youmightnotneedjquery.com/ https://youmightnotneedjquery.com/ I keep waiting for the equivalent www.youmightnotneedreact.com url to pop up.
- croisillon 2y agonot exactly that but there is http://youmightnotneedjs.com/ http://youmightnotneedjs.com/ and https://www.htmhell.dev/adventcalendar/2023/2/ https://www.htmhell.dev/adventcalendar/2023/2/
- krapp 2y agoNot according to the last couple of threads about it: https://news.ycombinator.com/item?id=25770858 https://news.ycombinator.com/item?id=25770858 https://news.ycombinator.com/item?id=7152068 https://news.ycombinator.com/item?id=7152068
- iLoveOncall 2y agoI've always found this website absurd since almost every example is harder to read and remember in native JS than in jQuery. It makes an extremely good case for jQuery IMO.
- forkerenok 2y agoThey don't claim it's clearer than jQuery. The pitch, as I understand it: if you only need a few of those operations, it may be better to forego adding jQuery dependency.
- lofaszvanitt 2y ago[flagged]
- deleted 2y ago[deleted]
- wackget 2y agoBut why? With mainstream websites pumping out literal megabytes of JavaScript, why spend time rewriting an entire library (with less features) to save 50KB?
- simonw 2y agoSome of us still try to ship websites that use less than 50KB of JavaScript total.
- happytoexplain 2y agoMaybe if we embraced small dependencies rather than saying "why bother?", then dependencies would become smaller?
- szundi 2y agoThis
- w4 2y agoNot relevant to this package in particular, but this line of reasoning baffles me every time I see HN comments about JQuery. So many posters argue against the use of JQuery because of its package size and bandwidth constraints, while simultaneously advocating for SPA frameworks that use orders of magnitude more bandwidth. Absolutely ridiculous cargo cult reasoning.
- happytoexplain 2y agoA. You're assuming they are largely the same people by extrapolating from your observations. It's impossible to actually know. 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.
- nashashmi 2y ago
- moffkalast 2y agoFinally a name that is perfectly fitting and describes the library surprisingly well.
- elaus 2y agoAssuming you mean that ironically. Unfortunately, the README doesn't reveal where the name comes from, but it is truly absurdly misleading, as if it came from a random generator...
- deleted 2y ago[deleted]
- luckylion 2y agoI assumed it comes from jQuery defaulting to $ as an alias for the jQuery function.
- moffkalast 2y agoNot sarcastic at all actually, I take you you've missed the absolute horde of dollar signs it uses in its syntax? Reminds me of this old joke: "Why do greedy developers all learn PHP? Because there's a lot of dollars in that."
- elaus 2y agoOh wow, I really didn't make that connection. Thanks! 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...
- EasyMark 2y agoFor some reason I would have preferred they called it “Cash Money”
- mg 2y agoBrowsers have become so nice to work with, that these days, I get away with just the following two lines of code to simplify DOM manipulation: 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: https://github.com/no-gravity/dqs.js https://github.com/no-gravity/dqs.js
- nashashmi 2y agoI really wish it was a native script to use qs and qsa, rather than something I have to add. FYI: I know you meant to give an example, but element tags with ID are DOM variables as well.
- wmanley 2y ago> Browsers have become so nice to work with, that these days, I get away with just the following two lines of code to simplify DOM manipulation: > > dqs = document.querySelector.bind(document); > dqsA = document.querySelectorAll.bind(document); 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?
- brightball 2y agoIncluded in multiple places?
- 0xCMP 2y agomodern browsers support the import syntax natively, so it really shouldn't be a lot of overhead to import it.
- notpushkin 2y ago
- openrisk 2y agoFine as an exercise but for a range of use cases what you really want is the smallest alternative to the bloated reactive js frameworks and alpine.js seems to be occupying that sweet spot.
- samdixon 2y agoThis seems pretty different from the functionality alpine provides, no?
- chmod775 2y agoHere's a stretch goal: use typescript template string magic to correctly infer the type of elements. For instance you can statically infer that $('div#name') will be a HTMLDivElement.
- hinkley 2y agoElixir and a few other languages have the pattern matching and type system that could pull that off but not a lot of languages do. Can you do that in typescript? I don’t see how.
- dimava 2y agoYou can, using `function $<S>(sel: S | `${S}${ ' '|'#'|'.'|'[' }${string}`): HTMLElementMap[T];` or 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/ 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" })
- totallykvothe 2y agoYou definitely can do that in TypeScript. The kinds of things you can do with generic inference and string literals are crazy
- norskeld 2y agoTypeScript's type system is Turing complete, so you can not only do that, but also some insane stuff like: - A SQL database implemented purely in TypeScript type system (https://github.com/codemix/ts-sql https://github.com/codemix/ts-sql) - Chess implemented entirely in TypeScript (and Rust) type systems (https://github.com/Dragon-Hatcher/type-system-chess https://github.com/Dragon-Hatcher/type-system-chess) - Lambda calculus in TypeScript type system (https://ayazhafiz.com/articles/21/typescript-type-system-lambda-calculus https://ayazhafiz.com/articles/21/typescript-type-system-lam...)
- dr_kretyn 2y agoWhat does the "modern websites" mean? It honestly sounds like "this only works in the latest chrome, and only on the latest windows and macos".
- fabiospampinato 2y ago"modern websites" means IE11+ for cash, it's a fairly old library.
- Cannabat 2y agoI remember using cash about 10 years ago. Was it under a different user back then? Ken wheeler maybe? Thanks for your continued work on it!
- fabiospampinato 2y agoYes exactly, at some point I asked to maintain it and kinda redid it. Now I kinda consider it "done", as in "maybe some more work would be put into it, but by end large I don't think it's going to change in the future".
- hinkley 2y agoThe way I see it once you’ve thinned the polyfills to next to nothing, the enduring feature of jQuery is the automatic list comprehensions. The ability to unselect all of the buttons in a form in a single call is still hard to match elsewhere. That and parent queries. 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.
- luckylion 2y agoNot having to worry whether some selector matches any elements is part of what makes jQuery attractive to many though. It's very "fire and forget", you send off your command to hide all .foo, and if there are any .foo they will be hidden, and if there are no .foo, nothing happens and you don't need to worry about it, much like CSS. If you write .foo { color: red; } and there isn't any .foo in the document it doesn't do anything but also has no negative side-effects (except that tiny overhead).
- bussyfumes 2y agoJust had a script today that fires in 2 contexts and ran into an error where the element I attach a handler to doesn't exist in one of the contexts which breaks JS on the page. Since I already had jQuery as a dependency in the project, in the moment it felt easier to replace the querySelector call with jQuery, which I did, instead of checking the querySelect result so I second this, the 'fire and forget' part still holds up very well even though the tree traversal pain points have mostly been solved by browsers.
- wwweston 2y agoExactly this. It's extremely useful to be able to say "with all document elements that matches this selector (whether there are any or not), do this." 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.
- deleted 2y ago[deleted]
- robertoandred 2y agoNot sure I’d call IE11 a modern browser. Aren’t they leaving more size/speed improvements on the table by supporting it?
- fabiospampinato 2y ago> Aren’t they leaving more size/speed improvements on the table by supporting it? Only tiny ones, I don't remember the details now, IE11 ended up providing almost all the same APIs.
- aargh_aargh 2y agoFrom the migration guide I learned a few things that jQuery can do (and Cash can't) that I didn't know and I'll probably use some time: https://github.com/fabiospampinato/cash/blob/master/docs/migration_guide.md https://github.com/fabiospampinato/cash/blob/master/docs/mig...
- aleclarsoniv 2y agoI used this initially in a browser extension I'm building. Ended up migrating to a JSX library instead, because jQuery turns into hard-to-reason-about code pretty quickly once you're past “simple app” territory (and I say this as someone who wrote my own jQuery-inspired library[1]). Right tool for the job, as they say. [1]: https://github.com/aleclarson/dough 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.
- AltruisticGapHN 2y agoI created a similar `$()` utility function for my projects albeit with 10 times less functionality. 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.
- PikachuEXE 2y agoI am using another one Umbrella JS https://umbrellajs.com https://umbrellajs.com
- jgalt212 2y agoThe primary reason we keep around and use jQuery is because most pages on our site rely upon datatables.net which relies upon jQuery.
- exodust 2y agoThanks. Didn't know about datatables.net looks very useful. 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!
- andai 2y agoI hear jQuery 4 is a jQuery alternative for modern browsers.
- geenat 2y agoFor those interested in jQuery alternatives- I've been waiting for jQuery 4.0 soooo long I ended up making my own jQuery with some key differences: * 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 https://github.com/gnat/surreal
- hu3 2y agoThis is great! 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/sveltejs/kit/issues/2221 https://github.com/sveltejs/kit/issues/2221
- Izkata 2y agoConflicting documentation: 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?
- slmjkdbtl 2y agoI'm confused, how is this helpful beyond having some aliases for already existing web apis?
- k__ 2y agoIn theory, I love all those tiny libs and frameworks 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
- nedt 2y agoBack in the days when trying to slim down JS I used https://github.com/filamentgroup/shoestring https://github.com/filamentgroup/shoestring Main reason was because they had offered a custom build to only add what you really need. It looks like cash has that as well, just bit more hidden in the documentation https://github.com/fabiospampinato/cash/blob/master/docs/partial_builds.md 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.
- nsonha 2y agoIs it just me who doesn't need jQuery or anything like that anymore? What kind of crazy direct dom query/manipulation do you need? The manipulation should be on the backing state, and then the dom should just derive from that, such as with data binding.
- deleted 2y ago[deleted]
- dzonga 2y agoglad sanity is returning to the world bit by bit 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.