Hacker News new | ask | show | jobs
by doomroot 809 days ago
I believe memory leaks to start
3 comments

Memory leaks can occur when a component adds events to an element outside of the component (such as the window) and then gets removed from the DOM without removing the event handler from the window. This is solved in native Web Components by the mount/unmount methods where you can run code to remove event listeners when the component has been unmounted.

For other event listeners, they get removed when the DOM element is removed.

The frameworks do not solve this to any greater degree. They also just make everything invisible and behind-the-scenes and hard to debug due to their declarative nature, but that is another topic.

Example with web components in all frameworks https://webcomponents.dev/blog/all-the-ways-to-make-a-web-co... and an other version to experiment with https://jsbin.com/yiviragiba/8/edit?html,css,js,console,outp...
Removing event listeners upon some component being removed actually sounds like a great use case for the new FinalizationRegistry API[1]

[1]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...

This is one of those points where you need to link to some kind of data or conclusive result actually showcasing this, because you're arguing against a pattern that's been in browser ecosystems for decades. I've done this for larger applications and haven't experienced issues.

Being charitable, the best I can imagine right now that'd cause memory leaks is someone running into the old school JS scoping issues and capturing something in handlers that they shouldn't. That's not the handler itself that's the problem, though - that's the developer.

(Yes, we could rant on and on about the poor design decisions that JS has built in, but that's been beaten to death)

Are you implying that there are memory leaks in browsers' internal implementation of events? Because my take is that the problem is with "user space" scripts not cleaning up after themselves, and I don't see how that would get better by adding yet another API to be mindful of.
I believe this would be more related to something like memoizing a DOM structure in a "Live" listener that is later removed from the DOM but not garbage collected due to the reference in the event listener. As the poster mentioned, developer error -- not a fundamental language or browser implementation flaw.
If a language or browser implementation can't reclaim this unused memory thus creating a memory leak, that arguably is a flaw. It's literally a DoS attack vector that can be exploited by the untrusted scripts that run in the browser sandbox.