I am registering a click listener on a DOM element via jQuery.on(). If later on that element is removed from the DOM -- maybe indirectly, e.g. by by replacing some parent's content via $(parent).html(...), should I still bother to remove my handler via jQuery.off()?
Even if the element will no longer trigger any event, I am worried about potential memory leaks. Does either jQuery or the browser take care of that and discard all registered handlers once an element is removed from the DOM?
Even if the element will no longer trigger any event, I am worried about potential memory leaks.
This is very good concern. To answer your question, take a look at $.fn.html implementation. From there you will learn that html will try to clean up stored event data:
// Remove element nodes and prevent memory leaks
if (elem.nodeType === 1) {
jQuery.cleanData(getAll(elem, false));
elem.innerHTML = value;
}
So in this case manually calling .off() is not necessary. However..
You need to remember that you should never ever try to remove elements with native methods like removeChild or setting innerHTML, since in this case there will be a memory leak for sure (if some data is stored, events are registered by jQuery, etc.). In this case it's more reliable to actually deregister event handlers with .off method. Or better use event propagation and instead or html('') use $.fn.remove.
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