Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MutationObserver automatically disconnect when dereferenced?

Tags:

javascript

I'm not super familiar with the internals of JavaScript and garbage collection. I want to avoid circular references that could create memory issues when using a MutationObserver, and I'm aware that with the wrong GC assumptions, I could make the MutationObserver hold a reference to an element that would prevent the element from getting GC'd.

When an element is removed from the page, the MutationObserver instance is no longer referenced, but it is still observing the removed element, would it stay in memory and continue to observe the element?

Maybe that's a question for a particular browser implementation? I don't want unnecessary/defensive code cruft, but I'd hate to make a subtle memory leak this way.

like image 615
Woahdae Avatar asked Dec 06 '25 11:12

Woahdae


1 Answers

No, it would not stay in memory. Anything that is not referenced from window (the global scope) downwards is viable for garbage collection, circular references in any form are not a problem. Wether the engine collects it and when is up to the engine.

like image 155
Jonas Wilms Avatar answered Dec 09 '25 01:12

Jonas Wilms



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!