After an element is removed from the DOM, will its event listeners automatically be unregistered and their referenced resources (closures) cleaned up? If yes, will the answer change if some non-event listener code holds a reference to the element?
My specific concern relates to "pseudo-navigation" where the unload
event is fired and most of the document is replaced (and of course many replacement elements also register event listeners), but there might be several pseudo-navigations before another full-page load occurs. So I'm wondering whether it's necessary to track all added event listeners and remove them manually when unload
fires to avoid leaking any resources they reference.
(Notes: In my case, "use jQuery/[other js library] to handle it" isn't a valid solution. I'm interested in compatibility with IE8+ and reasonably new versions of other browsers.)
Event handlers will be removed and cleaned up when the DOM element is garbage collected as part of the garbage collection process in modern browsers. Note, this is different than when it is removed from the DOM because if any Javascript has references to the removed DOM element, it will be retained and will not be garbage collected.
Note: this is the intended functionality - some older browsers might have some bugs in this regard. Older versions of IE are the most prone to issues with garbage collection issues. Many other types of GC issues are documented with older versions of IE, though I'm not aware of any specific issues in the case you describe.
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