Assume I have a javascript function createMyElement
which returns a node that can be inserted into an HTML document.
In order to function properly, the code of the node created by createMyElement
has to listen for events on the global document
at least as soon as it is inserted in the document.
My first attempt was to add DOMNodeInsertedIntoDocument
and DOMNodeRemovedFromDocument
listeners to the node at creation time that add and remove the needed listener on document
in turn.
However, the mutation events are deprecated by now (and don't seem to work reliably across browsers), so I am looking for a better solution.
Adding the listener for events at document
at the creation time of the node would work. However, this doesn't seem to be a good solution as it would create memory and performance leaks: Even after the node was being removed from the document again and not needed anymore, the listener (and its references to the node) on the document
would still persist.