11

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

Modular
  • 6,440
  • 2
  • 35
  • 38

1 Answers1

13

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.

Community
  • 1
  • 1
Modular
  • 6,440
  • 2
  • 35
  • 38
  • This doesn't seem entirely satisfactory, after running some tests. If you keep a WeakRef to the MutationObserver and log it at any interval, the WeakRef will keep containing a reference to the MutationObserver even after removing all involved DOM nodes, calling disconnect(), and manually triggering garbage collection from DevTools. – DanielM Sep 21 '21 at 10:20
  • 2
    That said, MDN is rather clear about it in https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver/disconnect#usage_notes: "If the element being observed is removed from the DOM, and then subsequently released by the browser's garbage collection mechanism, the MutationObserver is likewise deleted." I just can't manage to see this in practice :-/ – DanielM Sep 21 '21 at 10:22