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
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.
disconnect() The MutationObserver method disconnect() tells the observer to stop watching for mutations. The observer can be reused by calling its observe() method again.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With