If a DOM Element is removed, are its listeners removed from memory too?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Modern browsers
Plain JavaScript
If a DOM element which is removed is reference-free (no references pointing to it) then yes – the element itself is picked up by the garbage collector as well as any event handlers/listeners associated with it.
However; if there are references that still point to said element, the element and its event listeners are retained in memory.
jQuery
It would be fair to assume that the relevant methods in jQuery (such as
remove()) would function in the exact same way (consideringremove()was written usingremoveChild()for example).However, this isn’t true; the jQuery library actually has an internal method (which is undocumented and in theory could be changed at any time) called
cleanData()(here is what this method looks like) which automatically cleans up all the data/events associated with an element upon removal from the DOM (be this via.remove(),empty(),html("")etc).Older browsers
Older browsers – specifically older versions of IE – are known to have memory leak issues due to event listeners keeping hold of references to the elements they were attached to.
If you want a more in-depth explanation of the causes, patterns and solutions used to fix legacy IE version memory leaks, I fully recommend you read this MSDN article on Understanding and Solving Internet Explorer Leak Patterns.
A few more articles relevant to this:
Manually removing the listeners yourself would probably be a good habit to get into in this case (only if the memory is that vital to your application and you are actually targeting such browsers).