Should I call jQuery.off after removing the DOM element?

I am registering a click listener on a DOM element via jQuery.on()

. If this element is later removed from the DOM - perhaps indirectly, for example. by replacing some of the parent content through $(parent).html(...)

, should I still be worried about removing the handler through jQuery.off()

?

Even if the element no longer fires any event, I am worried about potential memory leaks. Does jQuery or browser support escape and discard all registered handlers after an element is removed from the DOM?

+3


source to share


2 answers


Even if the element no longer fires any event, I am worried about potential memory leaks.

This is a very good concern. To answer your question, see the $.fn.html

implementation . From there you will find out what html

will try to clear the 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 a manual call is .off()

not required. However..

You should remember to never try to delete elements using your own type removeChild

or setter methods innerHTML

, as this will most likely result in a memory leak (if some data is retained, jQuery logged events, etc.). In this case, it is more reliable to actually unregister the event handlers with the .off

. Or is it better to use event propagation and html('')

use either instead $.fn.remove

.

+5


source


It is better to call jQuery.off before deleting the node, especially if it is a single page application that may contain many registered events.



0


source







All Articles