Search code examples
jquerymemory-leaks

Could this result in a memory leak?


Consider the following two approaches of doing the same thing in jQuery:

// Approach 1
const $element = jQuery(...); 
$element.on('click', () => { 
    $element.addClass('ok');
});
// Approach 2
const $element = jQuery(...); 
$element.on('click', (evt) => { 
    const $element = jQuery(evt.currentTarget); 
    $element.addClass('ok');
});

If later on, somewhere else in the code, the $element.remove() is called, could any of these approaches result in a memory leak (or would any of these two approaches to be more likely in resulting a memory leak)?

If I understand correctly, the $element.remove() method, should also destroy the event listener on the element, and I presume that if the destroy is called, no memory-leak should occur.

On the other hand, what would happen, if no remove would be called, only the $element would be removed from the dom (by let's say, destroying one of it's parent elements and replacing it with another element)?


Solution

  • If you use .html, .empty or .remove to "destroy" elements, jQuery will internally remove all data and event listeners to the element and its children to prevent such memory leak.

    As written in the docs:

    https://api.jquery.com/html/#html2

    https://api.jquery.com/remove/

    https://api.jquery.com/empty/