Woahdae
Woahdae

Reputation: 5051

MutationObserver automatically disconnect when dereferenced?

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.

Upvotes: 3

Views: 391

Answers (2)

lonix
lonix

Reputation: 20549

From MDN:

If the element being observed is removed from the DOM, and then subsequently released by the browser's garbage collection mechanism, the MutationObserver will stop observing the removed element. However, the MutationObserver itself can continue to exist to observe other existing elements.

So if the MutationObserver was observing multiple elements, it will remain in memory.

If it was only observing one element, then hopefully it will be eligible for garbage collection (but that is not documented and so not guaranteed; it would depend on the browser).

Upvotes: 0

Jonas Wilms
Jonas Wilms

Reputation: 138257

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.

Upvotes: 2

Related Questions