Are JavaScript event listeners cleaned up automatically?
Asked Answered
D

1

10

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.)

Discriminate answered 17/1, 2015 at 1:40 Comment(2)
possible duplicate of Will events automatically be unbound after the element was destroyed?Changteh
The proposed duplicate is somewhat specifically about jQuery. I can't use jQuery.Discriminate
M
11

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.

Musetta answered 17/1, 2015 at 1:44 Comment(3)
Do you know of any sources with more details about this? I was having trouble finding anything, probably because I couldn't think of the right search terms.Discriminate
@Discriminate - Search for "DOM memory leaks".Musetta
Be very careful of referencing DOM elements in closures (and make sure you're aware when you're creating closures) as this is one of the larger sources of references to otherwise deleted nodes (and by extension, their event handlers)Changteh

© 2022 - 2024 — McMap. All rights reserved.