Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are JavaScript event listeners cleaned up automatically?

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

like image 576
ecraig12345 Avatar asked Jan 17 '15 01:01

ecraig12345


1 Answers

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.

like image 176
jfriend00 Avatar answered Sep 20 '22 23:09

jfriend00