Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should MutationObservers be removed/disconnected when the attached DOM node is removed like removeEventListener for events?

A nearly identical question is found here: Should an IntersectionObserver be disconnected when element is removed

I haven't found documentation that states what should be done when an element--with an attached MutationObserver (MO)--is removed from the DOM. The API doesn't provide a remove method like removeEventListener, just a temporary disconnect method that only concerns the child nodes. Garbage collection would come along eventually, but seems like it could get messy/bloated in a SPA webapp. I could use the delete keyword to remove the variable holding the MO, but I've read caveats in doing that (not necessarily for MOs) instead of letting garbage collection handle it.

So I'm looking for official information such as "MOs are removed when the associated DOM element is removed," or "MOs are automatically garbage collected when the assigned variable is no longer used", or "MOs should be deleted from their parent object if they are no longer being used," etc.

The spec: https://dom.spec.whatwg.org/#mutation-observers

like image 590
Modular Avatar asked Jun 29 '18 16:06

Modular


People also ask

Should I disconnect mutation observer?

If you need your MutationObserver only once (e.g. for initialization or whatever), you should disconnect it after it's no longer used. This might or might not free some memory, but it will certainly decrease CPU load.

How to Disconnect MutationObserver?

disconnect() The MutationObserver method disconnect() tells the observer to stop watching for mutations. The observer can be reused by calling its observe() method again.


1 Answers

As I was researching the topic more, it seems that I came across the answer.

In the eyes of garbage collection, MOs are tightly coupled with the DOM elements, whereas their descendants are loosely coupled. So it appears that you remove the DOM element whenever, and garbage collection is supposed to handle the rest.

Official answer https://dom.spec.whatwg.org/#garbage-collection:

4.3.4. Garbage collection

Nodes have a strong reference to registered observers in their registered observer list.

Registered observers in a node’s registered observer list have a weak reference to the node.

like image 80
Modular Avatar answered Oct 31 '22 00:10

Modular