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.
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.
来源:https://stackoverflow.com/questions/51106261/should-mutationobservers-be-removed-disconnected-when-the-attached-dom-node-is-r