Readit News logoReadit News
davnicwil · 6 years ago
Great resource, I've bookmarked it.

You know where vanilla JS still has a legitimate usecase in the era of SPAs? Landing pages.

- Mostly static HTML, time to first render is critical, all you want is a little bit of (progressively added) flair

- Can be inlined for instant loading/execution, no bundle download (or SSR) necessary

- Code has low volume and scope so structure / spaghetti isn't a concern

- You can separate it out from the rest of your SPA bundle(s), so shipping changes is completely decoupled from your SPA CI/CD process and can be done as frequently as you like and very quickly

pjmlp · 6 years ago
> You know where vanilla JS still has a legitimate usecase in the era of SPAs? Landing pages.

Well, for me my framework is vanilaJS, anything else only when there is customer demand.

Then they get surprised how fast everything runs.

hailk · 6 years ago
Interesting. Can you elaborate on this. What do you use this vanillaJS framework for? How do you do DOM manipulation? How much traffic do you get from what you've built using this?

I've heard doing document.getElement... and then modifying the DOM is costly.

satvikpendem · 6 years ago
Yes, landing pages are places where you can use static HTML, CSS, and JS. However, React (and similar frameworks) might still be better, especially with a landing page with multiple parts. This is because React combines two different paradigms, one of creation and one of distribution.

In creation, React breaks up large parts into smaller components. In distribution, it renders them at runtime, not build time (with a standard create-react-app app). However, there is no reason to have both at once. Components make the page easy to reason about, and they can be used to compile a site at build time, as Svelte does. React also has its own libraries for this, like Gatsby and Next JS. You do say that the landing pages have low volume but they can certainly grow to encompass a larger amount of things, such as multiple feature pages or a blog, so I'd rather not rewrite everything later on.

You could also use Web Components but they don't have as much support and are generally not as good as React (one can disagree of course), so I like to use React + Gatsby to build the pages at compile time and use them without any Javascript whatsoever [0] but still have the developer experience of creating a page via components.

[0] https://www.gatsbyjs.org/packages/gatsby-plugin-no-javascrip...

brailsafe · 6 years ago
I really feel like React and components in general, or almost any framework is probably overkill for most basic websites and even apps can make things harder to reason about than previous architecture styles. Especially so if there is a tendency to decouple at a very granular level.
Scarbutt · 6 years ago
Components are not unique to react. Most template libraries have them.
zemnmez · 6 years ago
you can get all these benefits by pre-rendering and hydrating using a system like react-snap. this means static rendered html is served and the react control is then re-added, or ‘hydrated’ into the DOM content
gboss · 6 years ago
Depending on how "hydration" is done it can still waste cpu cycles and hurt time to interactive on mobile devices.
bryanrasmussen · 6 years ago
are you sure you can get all these benefits?

- You can separate it out from the rest of your SPA bundle(s), so shipping changes is completely decoupled from your SPA CI/CD process and can be done as frequently as you like and very quickly

I mean sure I guess I could do a lot of extra work to separate it out, it's true. But the real benefit of a vanillajs landing page is stuff is simple, and getting all the benefits by pre-rendering and hydrating using a system like react-snap sounds difficult.

If we follow the old saying Simple things (to say) should be simple (to do) it implies to me that Difficult things to say will be (relatively) difficult to do.

Lammy · 6 years ago
- You can include a deferred reference to a resource you want to be cached for other pages, like web fonts
zoom6628 · 6 years ago
This site is a real gem. Clean, simple, and minus the excessive complexity and obfuscation caused by frameworks. Doing & Learning things in plain JS we can learn fundamentals.
dgb23 · 6 years ago
I agree!

The MDN docs are from my experience the best browser frontend reference available.

This site however covers a different need: guide/howto oriented documentation, which is often what you want.

> Doing & Learning things in plain JS we can learn fundamentals.

To this I have to add that I often do write plain JS supported by only a few, small libraries such as is.js, axios, json-schema and so on. This is regarding small to medium sized projects and/or features.

This can easily save time, setup and mental energy, as long as one follows a consistent, simple structure. And on top of that, the fewer dependencies you have, the less friction.

But it also means that one has to have a bit of a deeper knowledge of the available frameworks and tools, which can manage complexity with growing features, because you add them incrementally and only when needed and so on.

duxup · 6 years ago
MDN is great as if you're reading the manual with all the details and etc.

But like a lot of raw manuals sometimes you read it and wonder "Wait.. why would I want to do this again? Does this even do the thing I started looking for?"

Some of their examples have actually evolved to be a bit more akin to more usage based rather than raw specs.

I do appreciate the other sites that are more "You want to..." as a complement to MDN and such.

Kwantuum · 6 years ago
Honestly, while axios is nice to have on the server side, the websocket API in the browser is very simple to use. Which IMO is a consistent theme with modern browser APIs.
onion2k · 6 years ago
I don't like it because it's basically wrong, or if I'm being more charitable it's only telling you half the stuff you need to know. Take this page as an example - https://htmldom.dev/select-an-element-or-list-of-elements

Firstly, it doesn't tell the reader that every method of selecting elements listed is available on both a Document and an Element. document.getElementsByClassName selects everything in the page with that class name. Element.getElementsByClassName selects every child of an element with that class name. If you're wrangling a huge page using one is better than the other. Chaining calls is really useful eg document.getElementById('users').getElementsByClassName('admin').[1]

"Select an element by given ID" using getElementById() does select a single element on the page with that ID, which is right, but browsers don't enforce ID uniqueness so you're only getting the first element with that ID. That's a very common gotcha for devs who are new to this. (React would tell you if you've not got a unique key.)

.querySelectorAll() does not return a list of elements. It returns a NodeList, which is different to the HTMLCollection that the other methods return. For a start, NodeLists aren't iterable in the same way as HTMLCollections. You can use forEach but you can't use map. That's going to throw a lot of devs a curve ball.

Worst of all though, it doesn't mention .querySelector() for picking individual elements. Why would you miss that out?

[1] The page that does talk about selecting children (https://htmldom.dev/select-the-children-of-an-element) of an element suggests using an element's childNode array. That's horrible. There could be all manner of strange things in there. Just use an element.querySelector() call.

austincheney · 6 years ago
> Firstly, it doesn't tell the reader that every method of selecting elements listed is available on both a Document and an Element.

https://developer.mozilla.org/en-US/docs/Web/API/Node/nodeTy...

Just about everything on the Element node type is available directly on the Document. The document is actually a node type in the DOM. In JavaScript the DOM methods are populated on the global objects Element and Document and that is visible in the browser console with:

    Document.prototype
You can see that the prototypes are almost but not exactly identical and both inherit from the global Node object. The page could have dived into that level of detail, but I think that largely misses the point. Most JavaScript developers are irrationally scared to death of the DOM and that page is trying to be a friendly low friction reference. If somebody were really looking for that level of granularity they could go to MDN or the DOM spec.

> but browsers don't enforce ID uniqueness

Actually, the browsers do. This isn't a browser shortcoming. It is an HTML shortcoming. If the code were parsed as XML the browser would point to the location of this violation.

> .querySelectorAll() does not return a list of elements. It returns a NodeList

Same thing. Node lists are iterable lists but are not a form of Array where the only practical difference is that a node list does not have the Array.prototype methods.

> The page that does talk about selecting children (https://htmldom.dev/select-the-children-of-an-element) of an element suggests using an element's childNode array. That's horrible. There could be all manner of strange things in there. Just use an element.querySelector() call.

Suggesting reliance on the convenience of the querySelector method is bad advise, especially from a learning and reference perspective. The querySelector method executes thousands of times slower than the other more specific methods because it requires a parse step. Also I see no danger of using the childNodes property. Simply don't make the blanket assumption that everything in the DOM is limited to element and text node types.

eMSF · 6 years ago
>.querySelectorAll() does not return a list of elements. It returns a NodeList, which is different to the HTMLCollection that the other methods return. For a start, NodeLists aren't iterable in the same way as HTMLCollections. You can use forEach but you can't use map. That's going to throw a lot of devs a curve ball.

querySelectorAll does return a list of elements. While technically a NodeList, you can't select non-element nodes with selectors which is why querySelectorAll never returns such.

Further, neither NodeList nor HTMLCollection implement methods like map, but both are quite iterable and in a similar fashion (by converting them to Arrays or using Array methods with them, like with other Array-like objects which JavaScript is full of). But if anything, NodeList is a "more" iterable type than HTMLCollection, as it does implement forEach itself, too.

I would certainly not recommend using querySelector for accessing an elements first child node or child element.

b0ner_t0ner · 6 years ago
Too bad this site doesn't remember your scroll position when you go to a page and hit the back button. For a site promoting vanilla Javascript, it didn't really need to be built with React.
yokohummer7 · 6 years ago
I was also annoyed by it not remembering the scroll position. The site doesn't live up to its name.
speleding · 6 years ago
I love the idea, but the very first example on there ("How to add a class to an element") comes with the disclaimer "isn't supported in IE 11". Everyone likes to support only modern browsers, but completely dropping support for IE is unlikely to be acceptable for most users.

For my own sites I conditionally include a shim for IE users so I can use vanilla JS and only IE is bothered by the longer load time, using <!--[if lte IE 10]> ... <![endif]-->

Deleted Comment

vbezhenar · 6 years ago
The problem with vanilla JS is not APIs, API is the easy thing. The problem is building proper architecture, so code won't quickly turn into spaghetti. With frameworks like Angular or React, it's much easier, as the general structure is dictated by framework and developer just have to follow good practice. With vanilla JS it's the wild west.
austincheney · 6 years ago
> With vanilla JS it's the wild west.

In my experience in the corporate world it's just as much the wild west even with using popular frameworks. Frameworks aren't a substitute for discipline or organization.

a_wild_dandan · 6 years ago
I wonder if those chaotic corporate experiences would've been far worse if not for the frameworks. They're just so useful for significantly constraining the solution space that you can't get too far into the weeds even when lacking discipline/organization.
ddek · 6 years ago
You’re write. I’m a tech lead in an ‘enterprise’ team, and the fight against spaghetti is so real.

I feel a lot of enterprise devs are older, and more set in their ways. It’a not just teaching them new technology any more - I have to fundamentally shift their approach.

All the while being 20 years younger and less ‘experienced’ than them.

It’s slow progress. Every time I relax control within a few hours I have to bring it back. One guy today tried to set up a deployment of a prepackaged service that involved building the service (in debug configuration), then running that. I had to explain that deployments out of /bin/Debug is a bit of a red flag. I’m not sure how you can miss that myself, but here we are.

mmcnl · 6 years ago
Ofcourse they are, I know a good bit of React and I can get a good understanding of any reasonably sized React project within a short amount of time _because_ it's a React project. People may still be people and do weird stuff, but that's a given in anything you do.
vinniejames · 6 years ago
The problem in corporate is too many developers trying to do things all at once 10 different ways, without anyone pushing to maintain consistency
pailhead · 6 years ago
In my experience this is not the case if you have experienced leads and architects. Just using a framework for the sake of using a framework can be just as bad or worse.
rukuu001 · 6 years ago
In my experience any team anywhere can turn any codebase into soup!

Strong tech leadership that provides good examples, institutes code reviews, establishes & follows standards etc is where nice code bases come from (even in tiny teams)

ulisesrmzroche · 6 years ago
A framework enforces some organization by its very nature, even the barebone ones. Otherwise they usually break. Plus, the popular ones will have a community that sets some standards, example, off the top of my head: python significant white space

Frameworks are not a substitute for engineering standards but anyone whose really interested in that, pay the bills interested, first thing they do is look for frameworks

Drew_ · 6 years ago
The difference now is it's only a "wild west" as far as app structure goes. Developers still need to put a lot of thought into component composition and app state to maintain a quality code base. Previously you had to do all of that AND put a lot of thought into how to update the UI correctly and efficiently. New approaches and frameworks removed the complexity of that last step.
edem · 6 years ago
I came here for this comment, thank you sir.
lhorie · 6 years ago
Sometimes I question if people claiming vanilla is spaghetti have actually used vanilla in any meaningful way or if they are just parroting what others have said. I find that a lot of times, it's the latter...

For example, something that I've come to find cumbersome about frameworks is that expressing things in terms of states makes it more convoluted to express mutations. For example: in vanilla, one sensible unit of organization would be something like this:

   const doThing => {
     input.value = value;
     input.focus();
     sound.play();
   }
   button.onclick = doThing
Expressing `input.value = value` is what frameworks generally shine at, but expressing the method calls is usually clunky, since they represent effects and those can't really be expressed in terms of state snapshots. So, expressing them in a "frameworky" way usually just looks like some variation of this, but on top of some abstraction (think, e.g. React's useEffect nested anonymous functions + refs + probably context and a provider because you're not going to just initialize your sound manager in your component, right?).

I think frameworks are about colocating things in some specific way, and whether the colocation structure is "good" is largely a matter of herd acceptance. W/ older frameworks like Backbone and Angular, the focus was on colocating things to fit a MVC paradigm. And people were totally on board with that. With Redux, one colocates actions for a particular piece of state. And people sing their praises about this structure too.

With reaonably written vanilla JS, it's not that there's no colocation. One colocates mutations related to a single action. It may not be a "cool kid" organization structure, but it _is_ structure.

Of course, one can write bad vanilla JS, but that's also true about any framework.

ng12 · 6 years ago
I would do this identically in React.

   const doThing = event => {
      const input = event.target
      input.value = value
      input.focus()
      sound.play()
   }
   ...
   <button onClick={doThing} />

bernawil · 6 years ago
Did you mean something like this?

   const doThing = event => {
     input.value = event.value;
     input.focus();
     sound.play();
   }
   button.onclick = doThing

ThePhysicist · 6 years ago
The problem with frameworks like React is that the version you’re using and its API will become outdated in no time. We started using React in 2014 and their approach to state management changed at least three times since then. Not to mention build systems, tooling and libraries. In my experience that leads to a large fraction of developer time (10-30 percent I’d say) just going into often pointless refactoring that is necessary to keep up with the framework ecosystem, because you don’t want to run “legacy code”. Most large organizations seem to accept that but for smaller ones it can be quite a burden.

The beauty of the native JS APIs is that they are relatively stable: things that worked 10 years ago still work today, and can be done in the same way. Also, standard adherence in browsers has become much better so if you do not need to support legacy browsers like IE you can get away with writing pure JS without any polyfills or frameworks.

dntrkv · 6 years ago
When has React's approach to state management changed?

The only change I know of is the introduction of the useState hook, but you don't have to use it.

The React team has done stellar job of maintaining a stable API with very minimal breaking changes. The only major breaking changes I can think of is the move of React.createClass to react-create-class and replacing the lifecycle methods through a slow and steady push over multiple major versions. I'm sure there were some smaller ones, but nothing that required any significant amount of time to fix.

As far as build systems and tooling, that's only as complex as you want it to be and doesn't have to change with the seasons. I've been using the same Webpack/Babel/React setup on one of my projects for about 7 years now with minimal work on my end (the only major upgrade was Babel 6 > 7, and Webpack 2 to 3, which took about maybe half a day to complete both).

jtms · 6 years ago
Browser APIs have changed quite a bit in the last 10 years. Yes, the same approaches are still supported, but there have been many additions and modifications to core APIs. Ten years ago you would have never dreamed of trying to build complex front end behavior without something like JQuery, but now it’s totally unnecessary as all browsers mostly adhere to the standards. I guess my point is I don’t think React has changed any more or less than browser APIs - both have just steadily updated best practices just like any other piece of software since ever.
jakearmitage · 6 years ago
This. Framework maintenance is something that takes a lot of time from our development team. Compared to other ecosystems (Python, Java), the frontend teams spend much more time dealing with updates to their stack (webpack, react).
redis_mlc · 6 years ago
> things that worked 10 years ago still work today

I have vanilla-js code from 1998 that still works unchanged in 2020.

jeremiep · 6 years ago
Been using react transparently through clojurescript's reagent for years and was never hit by any of react's API changes.

The problem usually isn't react, but that most projects using it directly use it wrong.

root_axis · 6 years ago
Why refactor if you don't see any value in it? There is no reason you have to refactor.
tarsinge · 6 years ago
In theory yes, but in practice even with frameworks codebases can turn into messes, and/or tends to become solid but completely frozen on a particular feature set. Small changes suddenly becomes daunting because the initial architecture needs to be changed to accommodate and surprise all is tightly coupled under the cover. With vanilla JS and spaghetti it's painful and boring but at least if I need to change a behavior on a page usually I'm done with a few lines of code. Edit: it's a tradeoff, but in early stages I found being able to make one the fly changes in a few minutes/hours to accommodate a customer instead of weeks (or never if it's too painful to evolve the perfect architecture) very valuable.

It really depends on the use case, and sure frameworks are awesome in the right context, but I think the current "best practice" of defaulting to one in any project no matter the business trajectory, product market fit maturity and team size is misguided.

Supermancho · 6 years ago
At my position, there are at least 5 different interpretations of how to do React. Each project has an overseer who enforces a particular philosophy/design. JS frameworks are frameworks. They don't make the problem easier, they just change the terminology and add new abstractions which inevitably turn into angel hair pasta.
protonimitate · 6 years ago
Agreed. This is my main issue with the "you don't need frameworks" rhetoric.

If you're a small team or a solo dev working on a simple app, and you know the source code very well, frameworks might not be the best choice.

However, if you've ever worked on a team of revolving contributors, constantly shifting requirements, or have any reason to reuse code across apps/repos, frameworks help immensely.

The biggest benefit to using something like React imo, is that when we hire somebody familiar with React, they can hit the ground running and start contributing immediately. Unless your app is dead simple, you won't be able to have the same velocity in a homespun framework (and given enough time, most "vanilla" apps turn into homespun frameworks).

ricardobeat · 6 years ago
> when we hire somebody familiar with React, they can hit the ground running and start contributing immediately

This is one of the selling points, but never really realizable in a large scale project. I've seen people become productive with an in-house template system, vanilla javascript + custom libraries even faster than on a "standard" React project.

As they emphasize in their own docs, React is not a framework. The amount of moving pieces you need around it for a working project ends up being more complex than your cut-to-size custom framework. There are many other positives to adopting standard tools, but this one is a red herring.

sgustard · 6 years ago
We've adopted a framework as a small team and it has nothing to do with onboarding new people. We adopted it became clear that if we stuck with vanilla JS, we'd end up re-building something like jQuery to keep our code and abstractions manageable. And then we'd build something like React, while doing a much poorer job of it. Once your app has some "click X and A, B and C should update" logic you quickly descend into a tangle of tracking dependencies by hand.
mettamage · 6 years ago
Isn't this also simply true in the corporate world in general? Frameworks and best practices of doing something means that things are standardized. Standardization means that a vocabulary is shared and people understand each other.

You want to make people as swappable as possible. At least that's how I look at it from a management perspective (not a manager, but one can dream).

superkuh · 6 years ago
The problem is every dev thinking that every single project has to be resume buzzword compatible and super complex to hide the complexity they're sure is coming. But these requirements really only occur if you're forced into them by working on something in order to make money. The web is more than just the commercial web.
Vinnl · 6 years ago
I'm using far more ridiculous, buzzwordy and complex tools in my non-commercial projects though. (In fact, that's usually the point of those projects.)
aikah · 6 years ago
> The problem with vanilla JS is not APIs, API is the easy thing.

Then the problem is really the API, if one needs to write tons of helpers just to make that thing bearable. Never had to write a framework on top of QT or WPF just to develop apps on these platforms. Web Components tries to make things a bit easier by allowing people to write their own widgets that know how to clean up themselves when removed, but it's not there yet apparently.

IMHO what the DOM needs is a good DOM diff API directly included in the browser. Right now it's either modifying DOM nodes themselves manually or just innerHTML string trickery, when wanting to update an entire tree of DOM nodes.

events are already a solved problem thanks to event delegation. It's DOM modification that is still painful.

This list of recipes doesn't solve the large front-end app at scale problem.

So personally right now, all I need IS a DOM-diff library. Using external widgets is a bit trickier, but with event handlers I can do required instantiation and clean-up provided the third party widget has the necessary event hooks.

cies · 6 years ago
> Then the problem is really the API

I think the problem of JS is not the APIs, it's the language itself.

> IMHO what the DOM needs is a good DOM diff API directly included in the browser.

Here you go, part of WebComponents:

https://developer.mozilla.org/en-US/docs/Web/Web_Components/...

> Web Components tries to make things a bit easier by allowing people to write their own widgets that know how to clean up themselves when removed, but it's not there yet apparently.

WCs aims to replace a lot of what is now React. As is "just the view and some encapsulation. With a the litElements lib (or some other) you also get some life cycle callbacks.

> This list of recipes doesn't solve the large front-end app at scale problem.

It did not claim to either.

My 2 cents: that problem is prolly going to be fixed by writing code that compiles to JS (or WASM). JS was the problem all along for big codebases; too quirky, too little safety, very easy to make mistakes.

mosdl · 6 years ago
Diffing isn't really needed - usually you either replace a subtree completely or change a few attributes, which isn't hard to write code for.

Diffing will always be expensive memory wise.

treespace89 · 6 years ago
I've been maintaining a complex web client for 14 years.

Every single time we have used a framework it has made development harder, and more fragile.

In addition within a few years either the framework is abandoned, or changed to be incompatible with what has been implemented.

Staying away from frameworks completely would have saved us more time in the long run.

nsomaru · 6 years ago
Could you share some lessons learnt and architecture tips?
bernardv · 6 years ago
The problem is that the Wild West and unnecessary complexity has just been shifted up a level or two as devs are now facing the Wild West of frameworks, de ops has turned into a monster with an unnecessary large toolbox.
grey-area · 6 years ago
It really depends how much complexity you shift to js - if most of the work is done on the server, you really don't need to lean on js very much and you can have relatively simple js which just annotates certain elements and updates content in response to user actions. You don't need a framework if you're not trying to shift the entire view layer to js.
jimmaswell · 6 years ago
The vanilla API is still a problem. It feels pretty verbose and limited when you're used to jQuery.

You really don't need any more than jQuery if you're just doing a few small things per page as opposed to a single page app or something.

acephal · 6 years ago
document.querySelectorAll?
gambler · 6 years ago
>The problem is building proper architecture, so code won't quickly turn into spaghetti [...] With vanilla JS it's the wild west.

This is a "problem" that I solved for myself years ago. It's not even that hard. I've started by noting that most of the issues with JS come from a few sources.

- Managing code dependencies.

- Navigating DOM. (Manipulating DOM is trivial.)

- Managing events.

- Synchronizing JS state with DOM state consistently.

If you pause to think about those, each of them has a straightforward solution that does not require a framework.

- Do not make libraries that directly depend on external code. Use DOM and HTML events for configuration and communication.

- Use CSS queries.

- Use timers or document-level events. They will continue to operate regardless of how elements change.

- Use DOM as your state storage. (Custom attributes + occasionally symbols.) This way your code itself is completely stateless.

There is more to it, but this is the foundation.

One of my favorite libraries is one that checks for specific attribute that contains a CSS query, then runs it, then outputs the result as a parameter on the original element. Couple dozen lines of code, countless applications. Best of all, you don't have to write any page-specific glue code. You load the library and it just works.

whatarethembits · 6 years ago
I hope then someone in your team is responsible for continuously documenting these patterns, however trivial they may seem to the author. I use frameworks for their documentation more than anything else. Maybe it's the UK developer culture but I haven't come across any codebase that has even remotely useful documentation in the past five years in three jobs. These "intuitive patterns" only exist in the senior dev's head. New comers have to either constantly ask or figure it out slowly by going through source files. Homegrown "simple and intuitive" solutions only benefit the rockstar who wrote them, not the other members of the team who are there now and who will come after the rockstar is gone.

Please use well documented frameworks, otherwise we're trading away the entire teams productivity in favour of the rockstar to have his say.

toastal · 6 years ago
I disagree with storing your state on the DOM. Querying the DOM can be pretty slow, but also now you're state is going to be stringy-typed which will involve parsers and a whole mess of reasons you don't want that. If you want to keep the logic simple, a view should be a function from a state/model to some 'visual' representation (be it DOM, canvas, Qt, ASCII, a quilt pattern, etc).
brylie · 6 years ago
What is the library you use for running functions based on CSS query?

I am working on a project where I initialize some DOM elements with data- attributes and control their visibility in response to a form input change event. It would be nice to somehow run the visibility check in more of a declarative/reactive manner without having to commit to writing my templates with a front end framework and build tooling.

Are there any reactive JavaScript frameworks that treat DOM and data- attributes as first-class citizens?

dntrkv · 6 years ago
I'd say the bigger problem with vanilla JS or any other imperative UI framework is exactly that, the imperative nature of these tools. React introduced the frontend world to a declarative approach for keeping the DOM in sync with your state. Until we have something similar in the native API, React and co. will continue to exist.
gregkerzhner · 6 years ago
Frontend development is a tricky beast because its hard to separate business logic from view logic. Since all your code relates to the view, its temping to just stick all your code into the view component or controller. This makes your components huge, untestable, and brittle. An great frontend developer will keep extracting models and business logic from view code until the view code is lean and really only renders. Some things are easy to extract like http calls or parsing logic. Other things are harder to see - like logic that might drive a step wizard. Even code like this can be expressed in plain models with plain functions, but its a lot harder to see and extract. Most people don't get there, or just don't care, so many frontend codebases end up with spaghetti view modules that you edit and pray things still work.
XCSme · 6 years ago
Agree, in the end you just end up creating your own custom framework.
rawoke083600 · 6 years ago
THIS a x1000 THIS !! There will never be a perfect framework, and jquery for a multi-person big project. It WILL be a mess in due time ! a Framework(even the most of the crappy ones) at least give you some opinionated standard ways of doing stuff. You can't pay me enough to work in jquery straight... Not saying it can't happen with frameworks. Just saying if you do a 100 projects with jquery or 100 projects with frameworks... There will be more chance the jquery ones will be a mess.
hinkley · 6 years ago
I learned jQuery on a project where everyone was expected to be full stack but only 2.5 of us could do any deep work on the front end.

I have done much, much harder things than convincing my coworkers to distinguish between 'important' nodes in a composition and incidental ones. Never put the incidental ones in your selectors.

If I'm a "Select All" checkbox, I need to find all of the checkboxes in "my" block of HTML that are not me, and select or unselect them. I don't give a shit if that's two divs up, one over and three down. Or if some IE bug means now it's three divs up and two over. I care about some top level element, and any of its children at any depth.

That's it. If I write my element selectors that way, I'm done and the layout people can put in a scrollbar later, or an expando. Also if I write my CSS the same way, it's easy to make these sorts of changes and it's easy to correlate the CSS with the Javascript that affects the same elements.

So much simpler than spending all day in a debugger when you're not in bug triage.

Most of those query selectors we relied on now have feature parity in the spec. I don't see why you couldn't use the same strategies in a vanilla situation today.

nsomaru · 6 years ago
Could you expand upon what you mean when you say a checkbox has "my" block of html? That a given element should not make changes in elements that are at a higher level in the tree?

Also, what are important and incidental nodes?

sergiotapia · 6 years ago
You can use Svelte and get pure DOM manipulation (fast, tiny) and a great framework to collaborate under.
MaxBarraclough · 6 years ago
On the topics of speed and lightness: does Svelte really have a proven track-record in real-world usage at this point? I understand that it has a neat compiler and some clever ideas behind it (no virtual-DOM), but still.
mythrwy · 6 years ago
It doesn't have to be wild west but I don't disagree it usually turns into that.

Before frameworks I spent a lot of cycles learning (usually the hard way) how to organize jQuery/JS code so it wasn't a total mess. I like to think I finally got it fairly maintainable for reasonable sized code bases. But by that time existing frameworks made a lot more sense so that's a bunch of thinking I'll never get back. I would guess I'm not the only one in this situation either.

Here's a really good book BTW if someone isn't aware of it.

https://addyosmani.com/resources/essentialjsdesignpatterns/b...

ehnto · 6 years ago
That's true of every language. It's the software developers job to build the architecture.

I am an advocate for frameworks in commercial projects, for ease of knowledge sharing, speeding up onboarding and having a strong architectural philosophy built in. But we can't forget that we are the makers, we make the frameworks. React and friends are Javascript, anything they can do we can do too.

I am happy to use them for work. But I find all frontend frameworks too tooling heavy and full of arbitrary details you have to learn once and promptly forget. In my personal projects I have a simple architecture I use to organise my code in vanilla JS, no tooling and it's simplicity lends well to small projects sprinkled with only some dynamic UI.

Deleted Comment

daxfohl · 6 years ago
The problem with frameworks is that they tend to drive the functionality of the site itself. It's easy for developers to start thinking in terms of what fun new things the framework allows rather than what the site actually needs.

I think frameworks are great, but you have to develop a self restraint from using every bell and whistle that's in it.

z3t4 · 6 years ago
A trick I use to make the JS code more maintainable is to wrap code into pure functions that returns an element. For example if you need an input that only accept numbers: var input = makeInputThatOnlyAcceptNumbers() where the function returns the element, and all nitty gritty state handling is done inside the function.
msla · 6 years ago
Are transpilers included in Vanilla JS? If not, then IE 11 and Edge prior to 15 don't support async/await, which would mandate two codebases for lots of use-cases. Similarly, lots of other stuff has uneven support, hence polyfill, which also isn't "Vanilla JS" sensu stricto.
tsukurimashou · 6 years ago
Well at least with vanilla JS you know your skills will be useful again in the future. With frameworks such as Angular or React, they can disappear and be replaced by the next flavor of the month pretty fast.
rimliu · 6 years ago
From what I have seen React is not better. It may not be spaghetti but then it is an exercise in architecture astronautics with way too many layers of indirection that is might as well be that spaghetti bowl.
x3haloed · 6 years ago
I completely agree. What's everyone's favorite extremely lightweight view frameworks? And for those of us writing SPAs, favorite controller and routing frameworks?
brylie · 6 years ago
LiteDOM seems promising

https://litedom.js.org/

rikroots · 6 years ago
> With vanilla JS it's the wild west

The thing I really, really like about Vanilla JS is that it has 0 (zero) dependencies.

If something breaks in Vanilla JS, you know with 100% certainty that it's your code that's failing. With a framework, it's mostly the fault of your code - but there's always an outside chance that it's somebody else's fault, buried deep in some 3rd party dependency that may-or-may-not have been maintained.

I like React and Vue (I love Svelte!) - on a well-planned project they can perform miracles. But I see no reason to hate on Vanilla: it has its place too ... if you know what you're doing.

nicoburns · 6 years ago
> If something breaks in Vanilla JS, you know with 100% certainty that it's your code that's failing.

If you're lucky enough to have the same developers for the duration of the project. Otherwise it'll be your predecessor who worked at the company 4 years ago's code. I've had to do far too much "reverse engineering" of "we don't touch that" code.

On the other hand, I've literally never encountered a bug in React. I guess it must have them. But I think not all that many.

bgirard · 6 years ago
> If something breaks in Vanilla JS, you know with 100% certainty that it's your code that's failing.

Or the browsers' code which is a bigger problem.

I've been burned in the distant past by a blackbox framework that didn't work well with my use case (JSF) so I can sympathize with your position. These days I'd rather hit the occasional framework and polyfill bug than deal with a wide range of interopt issues.

spankalee · 6 years ago
You do the same with "vanilla" that you do with frameworks: organize your UI into components and everything into modules.

You don't need frameworks for any of that.

SimeVidas · 6 years ago
Can confirm. Before I started using Preact, my client-side code was a large vanilla script. I would rather go work on a farm in Mongolia than go back to that.
dpcan · 6 years ago
"and developer just have to follow good practice"

Uhm, the exact same is true with vanilla js.

If you write crappy code, your code will be crappy even if you use a framework.

dexwiz · 6 years ago
> just have to follow good practice

Easier said than done when best practices shift every 6 months.

mosdl · 6 years ago
Doing interviews I've heard a lot of this - react is more efficient than using the DOM directly, etc but no one can tell me why - they are just parroting what they hear or get taught at coding camps and make a fool of themselves.

Dead Comment

danzig13 · 6 years ago
I think vanilla JS inside the components is the way to go.
ThomPete · 6 years ago
Only if you are building standard things IMO.

Dead Comment

rajeev-k · 6 years ago
Here's an example of a vanilla JS app with good architecture: https://github.com/Rajeev-K/eureka
x3haloed · 6 years ago
Looks like you structured your own MVC framework?
Leace · 6 years ago
Interesting pattern, first time I saw this:

        switch (true) {
            case cellA > cellB: return 1;
            case cellA < cellB: return -1;
            case cellA === cellB: return 0;
        }
Source: https://htmldom.dev/sort-a-table-by-clicking-its-headers

XCSme · 6 years ago
I think you can just do:

    if (cellA > cellB) return 1;
    if (cellA < cellB) return -1;
    if (cellA === cellB) return 0;
Why is the switch better? Or even (less explicit, but shorter code):

    if (cellA === cellB) return 0;
    return cellA > cellB ? 1 : -1;

marcus_holmes · 6 years ago
Switch statements indicate "it's one of these things", whereas in the series of ifs any of them could be true. Using a switch statement tells the reader that you expect one of these things to happen [0]. Using a series of ifs tells the reader that these things might or might not happen depending, and they're going to have to read each statement to work out which.

Your last version doesn't tell the reader what your intention is at all, and they need to work out what you're trying to do here. It's a lot less readable. Unless you're desperate for those bytes, it'd be better to use the switch statement for this case.

[0]: This gets a little weird in languages like JS where switch statements fall through to the next one if you don't break or return, but generally it still holds true.

simonsarris · 6 years ago
hah, well then you can of course continue...

    return (cellA === cellB) ? 0 : (cellA > cellB ? 1 : -1);

lmm · 6 years ago
It makes it clear that you're going to execute only one of the possibilities. Maybe that's clearer than a page full of ifs. But yeah, not particularly fond of the idea.
xxs · 6 years ago
both fragments are incorrect for NaN...

The correct is return a<b?-1: (a>b? 1 :0)

Dead Comment

smt88 · 6 years ago
You're seeing it for the first time because it's a bad pattern. It's confusing to a reader who is expecting a typical switch use-case, and it has no performance benefit over a series of if statements.

I don't know about V8, but a lot of compilers would have a harder time optimizing this because of the strange structure. For mature compilers and naive (i.e. not-yet-profiled) projects, it's better to write what you mean and let the compiler optimize it.

marcus_holmes · 6 years ago
Go does this too, and it's actually OK once you get used to it. The switch statement is still saying "it's one of these things"
planb · 6 years ago
I had to think for a sec to get this. And this already makes it worse than 3 if statements. Does anyone really find this more readable?
robto · 6 years ago
Coming from a lisp I often wish other languages had `cond` so I don't have to nest if statements. This looks like a poor man's cond.

So yes, I do find this more readable. It makes it clear that only one branch will get executed.

TheRealPomax · 6 years ago
you mean two if statements. The last case is a default return.
robocat · 6 years ago
The modern code is:

  return cellA.localeCompare(cellB); 
Because cellA and cellB are always strings:

   const cellA = rowA.querySelectorAll('td')[index].innerHTML;
If using a framework, you would generally have typed JSON data, which is better. For example, makes number columns sort correctly (example code above sorts ‘10’ before ‘9’).

Dealing with cells of tables is one area where code optimisations are needed if you care about performance and have a large table. There are multiple obvious problems e.g. looping over calls to querySelectorAll.

That switch(true) statement is not what I would expect from a more experienced developer. It is show-off code that looks cute and works, but the compromises are not worth it (statement order is not obvious, if you make a mistake and two cases are true then do you know which wins, it could easily deoptimise the JIT compiler because it is doing something uncommon, I would worry how debuggers and code compressors would handle more complex cases, and understandability is poor for new devs IMHO).

hacker_9 · 6 years ago
Interesting at first glance, but what is the performance of this? It looks like all cases would have to be evaluated before picking one, so even slower than an if-else-if.
XCSme · 6 years ago
Isn't it going to short-circuit with the return of the first truthy statement?
pvg · 6 years ago
That entire example in general reads more like a cautionary tale about coding yourself into overly-specific clunk in the service of staying 'vanilla'. The 'type' of things being sorted is hardcoded into the html of the table and the actual js code. The comparator function has specific logic just to handle ascending and descending sorts of that that particular table. This one 'simple' example is already more convoluted and brittle than it would be even if you 'reinvented' your own framework-like thing.
droobles · 6 years ago
I do all my personal mvps now in vanilla JS, I can get ideas fleshed out faster without fumbling over frameworks.
mschuster91 · 6 years ago
Out of random interest, not even jQuery? I find it immensely tedious to write out vanilla js compared to all the shortcuts that $ provides...
mellow2020 · 6 years ago
Knowing that jQuery ends up calling those very same functions, only often after jumping through a bunch of hoops, doesnt make me consider it a shortcut. Between auto-complete and copy and paste, I prefer slightly more "work" up front, and then zero needless work at runtime, than a bit of "magic" that ends up doing needless work every single time it is run.

But I have to admit, I don't care about compatibility beyond Firefox on the desktop, if I wrote stuff for a company on a deadline, or if I worked with other people on something, I would mind jQuery very little or not at all. But for my own stuff I make to spark joy, where I get to decide all of it, I want it as vanilla as I can get it.

hombre_fatal · 6 years ago
This line of reasoning only made sense in the old days.

For example, $.ajax() is strictly worse than the native window.fetch() -> Promise we have today.

I could see using jQuery in 2020 if your poor soul still has to support ancient browsers, but beyond that I suspect people only latch on to jQuery out of habit.

CSSer · 6 years ago
I'm not totally anti-jquery, but it helps to stay lightweight. If convenience is what you're after, you can always just bind querySelector and querySelectorAll to the document and assign each to a variable like this: https://dev.to/mrahmadawais/use-instead-of-document-querysel...
xingyzt · 6 years ago
QuerySelectorAll is widely supported and you can make your own shorthand for it.

  function $(query) {
    const result = document.querySelectorAll(query)
    if ( result ) {
      if ( result.length > 1 ) {
        return result
      } else {
        return result[0]
      }
    }
  }

woutr_be · 6 years ago
The main advantage of jQuery these days is all the plugins it provides, most (if not all) things you need on a website exist in jQuery. And I also found it really has messed up search results, search for anything javascript related, and almost all answers you find on StackOverflow are people suggesting to use jQuery. (Even when the author didn't ask for it)

The other day I was looking for a simple markdown editor, and it took me a while to find a decent vanilla one. (Ended up using https://simplemde.com)

throwaway55554 · 6 years ago
If they do this regularly, they surely have a personal toolbox of js code they can draw from that handle most everything jQuery would provide.
droobles · 6 years ago
Not even jQuery. The dom selector API is cohesive enough these days for my use.
tabtab · 6 years ago
Making decent UI's went from bicycle science to rocket science. VB-classic was easy to learn and easy to use, and you had coordinate control over where most things went on the screen. If your layout engine didn't put it where you had planned, you can just tell the widget to "go right here". You felt in charge of the screen, not some abstract layout layer with an attitude. A manager (person) could draw something on the back of a napkin and you could make it exactly match the napkin because you were in charge of exactly where things went. (Layout engines were optional then.)

The newer UI frameworks are round-about and confusing. They make it easy to get 80% of what you want, but that last 20% is bear, requiring long trial-and-error periods, unless you are heavily versed in them. Abstraction is only nice when it does what you want, not when it becomes "abstract art".

The price for "responsive" (client-side auto-placement) has been huge. In applications that are primarily for office desktops, their advantage is lost. Mouse and PC's is still where most real work is done. Instead we are using things like Bootstrap, designed for social networks, not real work. Glamour won over logic.

It's great job security for UI experts, but expensive for organizations because they need stack specialists whereby before a one-man-band (or 2) could make useful apps for less than half the cost and time without having to spend years with UI-Yoda to master some screwy layout engine.

Something is wrong.

reaperducer · 6 years ago
I currently maintain nine web sites, internal and customer-facing. For the last two years I've been migrating them off of the framework-go-round into plain old PHP→HTML + CSS + minimal JS where there is no other option.

Because I'm in healthcare, the web sites have gone crazy in the last four months, and there are updates upon additions upon updates of the additional content over and over and over. Think 14-hour days.

The sites that have been migrated out of the framework jungle can be updated in minutes to hours. The sites that are still stuck in framework hell can take hours to days.

When things happen (for example, when another state locks down), the framework sites get slow. The non-framework sites keep zipping along, which was my main reason for moving them in the first place.

The next time you're looking at a government or healthcare web site that doesn't have the latest COVID-19 information on it, look at the source code and try to figure out what it's been generated with.

debaserab2 · 6 years ago
So you profiled the sites enough to understand that the actual bottleneck for these sites was the framework CPU/memory overhead?

I don't know what the requirements of these sites are, but throwing out all the things you get with a framework such as a battle-hardened authentication system for "plain old PHP" hardly seems like a pragmatic decision. Was a full rewrite in a base language only really an easier/superior decision then finding more simply caching solutions (which many frameworks support out of the box)?

dmix · 6 years ago
I'm confused, are you saying using React/Vue is not practical for a small 1-2 person shop? As compared to what?

If frontend was bicycle science then I must have missed that in my 10+yrs writing frontends with JS+CSS...

> They make it easy to get 80% of what you want, but that last 20% is bear

JQuery was the standard before JS frameworks took off and it was a nightmare for anything besides smallish websites. It was good for 25-50% of what you wanted at most - everything else was completely different every project you looked at. Trying to manage a large application that any serious modern web-based SaaS company uses was incredibly difficult.

I started using Backbone.js before Ember/Angular was even a thing yet and it was the first serious attempt at building large JS-driven apps for browser and mobile. That was simpler because it mimicked Railsy REST/MVC set ups, plenty of analogies for backend people to learn from, but that turned out to be a poor way to create UIs and React/Vue/etc + Redux offered a thinner view layer with a very clean way to manage state and bind data to the UI.

JS frameworks stopped pretending they were traditional web server app/database in the browser. But rather one that reflected the reactive interactions which we are trying to model in real-life spread across various individual components... more like desktop interfaces, not recreating web apps backends in the frontend.

Vanilla javascript has improved quite a bit to lessen the need for JQuery, but even then managing state and mutations reliably, modelling data, coordinating async operations, only loading the JS you need on a particular page, code organization/modules, etc have all been made way easier with the new Webpack-driven frameworks.

But you can still use simple vanilla/JQuery if you only have a small project. There's still plenty of Jquery libraries being developed and simpler UI libraries like Bootstrap...

Unless you mean pure-HTML forms, which are extremely limited in terms of interactivity. But again they haven't gone away either if it fits your needs.

arc619 · 6 years ago
>If frontend was bicycle science then I must have missed that in my 10+yrs writing frontends with JS+CSS.

What you've said directly proves OPs point - you've missed the central message: UIs used to be bicycle science before everyone started using JS to make them.

They mentioned VB as in visual basic. GUIs with VB/Delphi are a case of dragging controls to where you want, pixel perfect every time on every desktop.

Web technologies are not designed for desktops but for building on top of HTML, so everything is an abstraction to get back to something that used to be possible with zero experience and sometimes even zero programming. For example, a simple notepad clone can be made in Delphi without a single line of code.

Now you need to 'full stack' to even know what's going on under all the layers just to place a control at an x,y and even then it can't be guaranteed because of all the different browsers, css edge cases, and other caveats.

godot · 6 years ago
The GP was saying VB-classic, implying that he's talking about windows desktop apps. I think that's what he's saying about layout engine stuff; layout engine is only a thing on web apps. Everything you're talking about is re: web apps, just older style web apps with JS+CSS in the past 10 years. For old school windows desktop apps you don't have to worry about client rendering, client's browser size, responsive (mobile vs desktop), etc. I believe GP is making an argument that most of these business-use web apps could've been windows desktop apps where the frontend takes half the time and team to build.
austincheney · 6 years ago
> JQuery was the standard before JS frameworks took off

jQuery was never a standard any more than it is now. It was popular even driving a bizarre fundamentalist cult of personality worship, but that by no means makes it a standard. In technology a standard requires wholesale adoption opposed to mere frequent consumption, even if not enshrined by a document (de jure). For example there was never a time that jQuery was required in any commercial capacity either to seek employment, perform work, or deliver a finished product. Claiming that I hated jQuery during its prime didn't stop me from closing a job interview, but it did turn a few heads.

* https://en.wikipedia.org/wiki/Technical_standard

* https://en.wikipedia.org/wiki/De_facto_standard

* https://en.wikipedia.org/wiki/De_jure

protonimitate · 6 years ago
This argument is typical hackernews upvote bait.

You can't honestly compare VB UI's to modern day web UI with a straight face. Following your analogy, making decent UIs is closer to rocket science because web apps are closer to rockets than bicycles these days.

I would love to see a drag-n-drop approach to web UI building that is responsive and fast. But I highly suspect the reason this doesn't exist isn't "great job security".

There's really nothing complex or difficult enough in React, Vue, or any other UI framework that can't be picked up by a competent dev quickly.

>Something is wrong

Yeah, the hivemind that loves to hate anything JS/front-end related and things "purity" is the only bar by which to measure things.

mb7733 · 6 years ago
> There's really nothing complex or difficult enough in React, Vue, or any other UI framework that can't be picked up by a competent dev quickly.

Honestly. Where I work we have a few undergrad co-op students who have just finished their first year of school. No previous React experience. They jumped right in and were useful on our React projects after about week. They just read some docs, asked a couple questions and played with our existing code. They're smart people but they're not x10 programmers.

We have other large projects that are a more "traditional" mix of DOM manipulation use jQuery, global CSS, etc. and introducing new hires to that is never as smooth. There are no docs as thorough as React's that explain the patterns established in those codebases (if there are any consistent patterns at all).

One thing to note, we make what I would consider to be web applications (for data management & analysis), not web pages.

noahtallen · 6 years ago
I agree with a lot of your points here. For example, I’d love to have a nice constraint system like you can have making an iOS. or even windows app. The problem is we have to work with HTML and the DOM, which aren’t nearly as nice to use out of the box as OS APIs. HTML/CSS/JS wasn’t designed for applications, it was built for basic document manipulation. But the pure accessibility and compatibility of the web is a better trade off for most products because it’s easier for people to find and use something on the web than downloading an app. So we’re forced to use worse tools.

I also don’t get the JS hate here. :) you certainly should not use react for your static resume site or blog. But react is a brilliant and necessary tool for web applications. If you don’t use it, you’ll end up making your own, probably worse abstraction for managing state and reactive updates.

Deleted Comment

lizardmancan · 6 years ago
I started the "hating" when pc promised everything would work on every computer. this just seemed impossible bordering idiotic. before this every screen had the same resolution. UI was horrifically easy! The c64 had characters in the font set that allowed drawing boxes. You can imagine but it was 10 times easier.

The problem with many layers of abstraction is that it borders the imposible if the layer abstacted to poorly suports something.

Take physical screen size and simple scaling to fit? Is it a tiny 1024px laptop or a giant tv? there is no solution I can think of

peterhunt · 6 years ago
VB classic didn't have a layout engine, so you had to do everything yourself. Making the window resizable required a huge amount of error-prone code that you had to change every time you updated the UI, and it often didn't work well. A classic VB6 bug was to resize the window larger, and then shrink it back down to the same size, and the layout would not be consistent despite the window returning back to the same size it once was.

The browser today lets you opt out automatic layout and instead specify fixed x/y/width/height coords with `position: fixed`.

It seems to me that your problem isn't the technology itself but perhaps the culture around it?

rkagerer · 6 years ago
I never found it error-prone. Perhaps meticulous. You had one event where you simply go through all your "dynamic" controls and set their position and size. I did it for all my applications, both simple and sophisticated. Worked like a charm.

The built in tooling got more flexible in .Net (eg. You could effectively "bind edges"), but I actually found setting all that up more time consuming in practice that just arranging everything myself in straightforward code (which also gave me more control over exceptions and edge cases).

ng12 · 6 years ago
> It's great job security for UI experts, but expensive for organizations because they need stack specialists whereby before a one-man-band (or 2) could make useful apps for less than half the cost and time without having to spend years with UI-Yoda to master some screwy layout engine.

My company has a very, very small number of UI experts who are tasked with making sure non-UI folks can build front-ends. It's been a rousing success. We own some documentation and a few tools to make starting projects easy. We teach an hour long workshop that covers everything (React, the npm ecosystem, TypeScript, best practices, etc) and then we let them have at it. It's been a rousing success and nobody has seriously suggested moving back to jQuery or any of the WISYWIG tools.

Sure there is a cost -- you need to hire at least one person with enough knowledge to cut through the bullshit and build the right tech stack. But once you've paid that cost once the payoff is massive.

ranit · 6 years ago
>> very small number of UI experts who are tasked with making sure non-UI folks can build front-ends

This looks an excellent approach.

>> you need to hire at least one person with enough knowledge to cut through the bullshit and build the right tech stack.

How do you ensure that this person will "build the right tech stack"? There are myriad of possibilities to go astray.

nsomaru · 6 years ago
How does this work? Has your company shared or consulted any resources regarding this?
edko · 6 years ago
There is nothing wrong. Before, you only had to care about your app running on a VGA monitor. Now, you have the possibility to make it run on devices of all sizes, resolutions and shapes.
tabtab · 6 years ago
Not really. Most productivity software still runs on desktops. We sacrifice too much to the Resize Gods without actually using them. It's like costly shrubbery insurance. (YAGNI.) Desktop GUI's were both easier to specify and were more productive to use. The "responsive" designs waste screen real-estate and require more steps to do the same thing, on average. The labor math usually says "no". There may be a subset of features that phone users need, but one can make a separate sub-app for those rather than poison the whole thing with mobile-oriented drawbacks.
qwertox · 6 years ago
Minutes ago I was reading this Stack Overflow question:

https://stackoverflow.com/questions/60997602/event-handler-g...

I was reading through the code, and was astonished at how this doesn't look like code anymore but a mashup of different languages and patterns in one single block of code.

The only framework I'm willing to tolerate at this point is Vue.js, which, with the help of http-vue-loader, is capable of nicely using components in a compiler-free workflow.

React may be excellent for teams, where there's a clear distinction between font- and backend development, but sometimes you just need to hack together a server with a minimalistic frontend which should just be editable via sftp, when you're building tools for internal use only. Vue.js is great for that, but I'm worrying that it will turn into the same thing Angular has turned into.

jackewiehose · 6 years ago
These fixed-size GUIs have already been shit in the 90s (remember the windows-dialog where you disable hiding of file-extensions? I think it's still there as of today and still annoying as always).

Now I have a big high-res monitor but can't read bad written applications like Steam because they don't honor my DPI settings.

No, we need flexible layouts. We always did.

amelius · 6 years ago
Let's be clear: we don't need flexible layouts, but it's nice when we have them.
D_Guidi · 6 years ago
> Something is wrong.

Even worse. We're stuck with html/js also for "desktop" apps, via the electon and similar. Basically, UI development is dead (Windows WPF is in maintenance mode) and if you want, as example, build some graphs you need to manipulate js in a webpage. A

unlinked_dll · 6 years ago
I'd offer a different take.

Users want to run your software on their system. You don't want to write software for their system, you want to write it for all systems. The output impedance of the developer and input impedance of the users is a function of how easy it is to write the app for all users and use it by any individual user. Optimal power delivery is achieved when I/O impedances are matches low. Efficiency is achieved at lower impedances.

JS/HTML/CSS is currently the optimal solution in that context.

UI isn't dead, it's more alive than ever. But since what works is what can get my product to the most people the fastest is on a web stack, that's the thing that's going to be used. And since the web stack is high impedance to begin with, anything I can do to lower that in terms of framework is going to be in demand, hence all the diversity we see.

parhamn · 6 years ago
> Making decent UI's went from bicycle science to rocket science.

But UIs are better than ever. How many Google Docs, Webflows, SquareSpaces, existed in VB-classic?

Let's give the space some credit. All this complexity wasn't for nothing.

harrygeez · 6 years ago
HN likes to downplay frameworks like React, Vue, etc., but people who work on modern web apps everyday know how insanely difficult/unmaintainable it is to write the same thing in plain JavaScript. And before you start saying "but I can build a simple HTML site and sprinkle with some JavaScript", the market has spoken – general web users like high fidelity web apps.

Whether you like inaccessible websites when you disable JavaScript is one thing, but don't dismiss useful tools that don't suit to your tastes. If you don't need to build a web app nobody's forcing you to.

grey-area · 6 years ago
HN likes to downplay frameworks like React, Vue, etc., but people who work on modern web apps everyday

Whenever I read the word 'modern' in this context now, I know the writer means javascript, and in particular one of the 'modern' javascript frameworks. I'm not sure quite how or when it acquired that meaning, but it seems to be used that way on HN frequently. I wonder how this word came to mean built with Javascript to some people? Do you genuinely see modern as synonymous with built in React, Vue, etc. or would you allow other approaches into the modern canon?

The similarities with the burn the old world then rebuild it anew attitude of early 20c Modernism are striking, so I suppose it fits, but it should not be used in the place of built with javascript, as the implication is nothing else is truly Modern.

Also what does high fidelity mean in the context of websites? Is this like high fidelity vinyl records with a warm sound? Do your frameworks have gold cables?

I think you'll find people here casting doubt on the requirement for web frameworks because there are many other ways of building websites (server side for example, the way this website you're using right now is built), there is no one 'modern' way. People build contemporary websites with a variety of tools, Javascript is not objectively better than other solutions IMO (in many ways it is obviously worse), and client side is not obviously better than server side, it's a pattern which has seen its popularity wax and wane and will do so again.

lhorie · 6 years ago
GP is not talking about JS frameworks, though. They're talking about layout constraint systems (the argument goes that CSS is harder to reason about because "width" might not mean physical width, since it could affected by margin, etc). The counter-argument, of course, is that there are many more types of devices now (e.g. using "desktop" experiences in an ipad, multiple screen resolutions, etc just to give a few counter-arguments to the notion that desktop is "simple")

As for frameworks: the market has indeed spoken, but not in the way you think. Consumers of websites rarely pay for the majority of websites they use. Employers, however, pay developers and the buzzword-chasing in resume building/interviewing cycles is real.

chrismarlow9 · 6 years ago
Nothing is wrong. Things got more complex and segmented and specialized in. That's just how an industry grows. I mean look at how many jobs, companies, and careers were created just around the invention of the "smart phone". In 1999 none of those really existed. Sure you could play the snake game on your phone, but I think the app store is a little more complex. Anyway, software pushes hardware to its limits, and then hardware pushes software to its limits, and the cycle goes around and around. With the invention of the smart phone, you got to see hardware push software to its limits, creating all these extra layers of coding that most of us old schoolers arent fond of. And now (in my opinion), the AI and Cryptocurrency GPU/ASIC movements are pushing hardware limits. So I'd expect to see lots of innovation in that arena and also lots of greybeards claiming "We dont need all these fancy different processors, back in my day we used a CPU farm and it worked just fine and why do we need all this".

On the other hand I know what you mean because I cut my teeth on coding VB6 and Delphi (Borland anyone?) applications in middle school (where are my Yahoo!, ICQ, AIM app masters at?). It was fun, and easier than todays craziness. And people wrote more client software instead of making everything a web service. We also had zone alarm and people got hacked left and right and windows BSOD and all the fun of the 90's and repeated unknown socket errors on winsocks. I also felt like the programming world had more curiosity and self-sufficient people, as opposed to being so heavily money, convert, social, latest tech driven. It feels like everything now is a rinse, repeat, sell to FAANG cycle.

axismundi · 6 years ago
That. I remember Borland C++ Builder. It was a pleasure to build compelling user interfaces with it, but it's best value was simplicity, the meticulously crafted library and great help system. That's how I got into programming. The big difference today are devices, especially screen sizes. We want to make apps now. Small, focused tools. Sadly often we have simple apps bloated beyond recognition for profit. That's partly why every gizmo in an app is not only pixels, no sir, it has to jump and blink and shout for attention. More layout engines won't make your app better. Keeping it simple and focused will.
gbuk2013 · 6 years ago
Every developer should definitely build a few dynamic applications using only DOM APIs.

After doing it several times, they will start building their own framework. At that point they should consider using an existing framework. :)

Dead Comment

icedchai · 6 years ago
We're using a document delivery system for application UI. That's what's wrong. This could've been fixed in the 90's, but it's too late now.

Deleted Comment

jandrese · 6 years ago
For CSS I have long suspected that this is intentional. The point was to let clients do what works best for them, and the page designers weren't supposed to be lining things up perfectly in nice squares.

Unfortunately the real world and the perfect world the CSS designers envisioned were two totally different things and as a result people have been fighting with CSS layout for years.

sireat · 6 years ago
What's wrong is we are trying to fit a round peg(general desktop apps) into a square hole(flowable document delivery model as envisioned originally by Berners-Lee).

It is easier to make UIs with Winforms, Qt, WPF, heck even with Actionscript it was more managable than with DOM.

The problem is that there is no unifying standard, no single vision. There are competing frameworks but they leak abstractions all over.

For example I am making UIs with ipywidgets which is basically JS on the front end and it at least a couple of abstractions too deep to fully understand it.

To emphasize how stupid making UIs using web is, let's take something simple like dropdown.

There is no such thing in the web standards, we use ul, ol etc and then we fake it/add another abstraction with a library or framework

In an ideal world dropdown would be a web component that could be imported, then be styled and events would be bound.

trog · 6 years ago
Uh, isn't a plain old HTML <select> dropdown as standard as you can get?
jcmontx · 6 years ago
The dogmatic React crowd is going to jump on your neck
DevKoala · 6 years ago
I am not a fan of React, but there is nothing about it that exacerbated the problems OP is talking out.

The web’s layout engine is just a PITA. I also feel much more in control inside a canvas. I can do anything I want inside it.

However, DOM manipulation is not a solution to layout issues, so I am not sure the OP’s gripe is that relevant to this tutorial.

aidos · 6 years ago
None of this has anything to do with react.
warent · 6 years ago
Can you please not do this here? Your post is obviously intended to be inflammatory and adds no value to the discussion.
jancsika · 6 years ago
> This approach isn't recommended because we can only attach one handler for each event.

Except when you do want that behavior. E.g., you only want to set one listener and have a stream of data coming in that can trigger various attachments/detachments to the same element(s) over and over.

With the ancient "on" methods you get a single method that you can replace at will. Unbinding happens automatically. For example, you can keep assigning to an anonymous function till your heart's content and there will only ever be one callback in that slot attached as the author states.

With the new, "recommended" methods you must manually track the state and unbind old callbacks. For example, you would have leaky behavior if you kept assigning anonymous functions with addEventListener. And you can't easily hack your way out of the state problem because the DOM doesn't give you a way to fetch the current number of listeners, reset them to default or really know anything about them.

So the recommended behavior does not include in its design the ability to achieve the useful old behavior.

But at least DOM does have a convenience method to toggle class that will save a good 10 seconds per year of dev time.

tln · 6 years ago
What's the context for that quote? The main page of the linked site doesn't have it.

I was wondering something similar while looking at https://htmldom.dev/toggle-password-visibility

This could be done inline with <input type="password" id="password" /> <button onclick="password.type = password.type == 'text' ? 'password' : 'text'">Toggle</button>

...instead of 10 lines of code. Is it ever ok to use the fact that window.elementID works? even for exposition? (it works in all browsers, not sure if its standardized...) Why use setAttribute? Again, setting via element.type = ... works in all browsers.

austincheney · 6 years ago
It does. https://htmldom.dev/attach-or-detach-an-event-handler

The idea behind addEventListener is that multiple handlers can be attached to the same event of the same node, whereas before handlers were property assignments that would clobber each other.

The disadvantage of addEventListener is that event handlers are associated with event listeners instead of with DOM nodes, which makes them more challenging to garbage collect and thus increases the memory space of your application. The way to keep the code clean is to use removeEventListener when the handler is no longer needed. Event handlers are rarely removed from the code though, because of a lack of discipline and because many times its hard to tell when they are no longer needed.

The biggest advantage of assignment by property approach is that it imposes simplicity. Simplify means to make fewer and complicate means to make many. When there is only one handler it is inherently the most simple approach, which greatly increases code cleanliness and forces a greater concern of code organization.

austincheney · 6 years ago
Coincidentally, I just commented yesterday about an interview experience I had about the DOM. I did not expect it to be so highly upvoted. https://news.ycombinator.com/item?id=22740897
dahart · 6 years ago
I don’t know if I would pass your test, but the outcome is more or less exactly what I would have expected. The vast majority of employed web devs do not use pure JS to manipulate the DOM because it’s incredibly tedious. That was true 5-10 years ago when the most popular option was JQuery, and now we have massive swaths of React where people don’t manipulate the DOM directly at all. And they get by just fine. Major commercial sites are built with little to no direct DOM manipulation.

Saying that you’re going to let people have time, use the web to lookup the answer, that there’s no penalty, etc., that seems blind to the fact that you’re signaling what it takes to pass the test as well as what people will be doing once they start working for you. I’m certain you lost the opportunity to interview some good candidates simply because they are choosing to not work somewhere that thinks pure JS is the only performant solution, and might not know that there are both good and bad ways to use JQuery, and/or functional reactive solutions that avoid keeping messy/buggy state around when you could instead re-render. I’m sure you also lost interviews because some candidates were basically told by you that already knowing how to manipulate the DOM via pure JS was what was required to ace the interview. They assumed, and reasonably so, that spending the hour showing you they didn’t already know how would result in not getting a job, so why bother with the interview right now? You might have sent several smart people off to study and do homework about it, but you don’t know that because they walked out the door.

So, while I do think it’s very useful to know how to use pure JS on the DOM, and I think your interview experience is interesting, the incredulity about it makes it seem to me like you’re not entirely taking responsibility for the implicit message that you sent to your candidates for the interview, nor that the outcome is fairly predictable.

austincheney · 6 years ago
The job position was for people to write A/B tests. A/B tests are a form of white hat hacking where code is injected into a page to manipulate or deface the page to test a business idea as an experiment.

It would not make sense to inject something like Angular or React as part of test code and would be detrimentally regressive to inject Angular or React targeted logic over an existing framework application without a more thorough consideration for second and third order consequences. An experiment is meant to be something that is created with the least possible labor since its not production code and short lived.

That said the most desirable approach was to manipulate the DOM directly since this achieved the fastest execution, provided the smallest risk/footprint, and was fastest to QA for regression.

---

In hindsight we learned a couple of things from A/B testing.

* In a page with a lot of asynchronously loading content everything can be precisely altered before the user can notice it. The more precise form of delay were recursive setTimeouts where the interval delay could be manually adjusted to the millisecond and there was never interval overlap. This took practice to know when and where to increase the interval rate without impacting the performance of other logic already in the page.

* The tests did not often reflect the actual business results compared to the production code written later. We found the test logic, even though it was just hacky throwaway code, was generally less defective and faster executing than the more thoroughly tested production code and so performed better than the actual results from the formally released code.

CSSer · 6 years ago
> Major commercial sites are built with little to no direct DOM manipulation.

Little implies some, and I think the average bundle is already large enough without saying, "Oh, just throw jQuery in there whenever you do need to do DOM manipulations.", which will happen. I built a React app a couple weeks ago where I had to use portals to integrate it with a legacy form solution because we didn't have time to rewrite the entire form backend to justify a custom frontend. It involved a fair amount of manual DOM manipulation, but it worked out fine. All said and done, it was probably ~75 lines in a file with a few more comments than usual. It doesn't make sense to add 30kb or even 10kb to the bundle for that, so yes, I would expect the average developer to know the base DOM api at least somewhat well.

edit: I completely forgot about TDD. Depending on your testing environment, you may need to understand the DOM api for mocking or base utilities built into the test suite.

combatentropy · 6 years ago
y-c-o-m-b · 6 years ago
I've been in about half a dozen interviews in the last 6 months and I've never had to do this problem, but honestly my first reaction would be "this is a trick problem" out of paranoia that it's too easy. I wonder if more anxious people fall into that trap and overthink it to the point of overwhelming themselves; kind of like freezing up during an exam that you studied extensively for.

My biggest issue in interviews is remembering the recursion formula with some of the sorting algorithms. I eventually get it, but I end up burning a good chunk of time figuring it out, so it looks bad. In my entire career (almost 15 years now?), I've never had to use recursion or sorting algorithms believe it or not. That's what I get for working strictly on enterprise business applications.