toni rmc
toni rmc

Reputation: 878

JavaScript/JQuery Garbage Collection and Events

Lets say I have this JQuery code which selects and gets an element by it's ID and than puts click event to it:

$( "someID" ).click( dummyCallback );

Later in the code I remove this element from the DOM by using replaceWith() or remove() functions.

$( "someID" ).replaceWith( "<div>New Element</div>" );

So this element will disappear from the DOM but what about the event that was bind to it? As I understand events are also objects and take up space in memory.

Will JavaScript/JQuery also clean up that object(s) as well or before removing the element I should do:

$( "someID" ).off( "click" );

Upvotes: 2

Views: 667

Answers (2)

dfsq
dfsq

Reputation: 193261

You should not worry about memory leaks if you remove element with dedicated methods like remove, replaceWith, html, etc. Those methods jQuery calles $.cleanData method.

For example, for replaceWith you can see that jQuery removes events and data objects from internal cache in order to prevent leaks:

if ( jQuery.inArray( this, ignored ) < 0 ) {
    jQuery.cleanData( getAll( this ) );
    if ( parent ) {
        parent.replaceChild( elem, this );
    }
}

Of course, you should never remove elements with pure DOM methods if those elements has jQuery event listeners/data associated with them.

Upvotes: 3

Halcyon
Halcyon

Reputation: 57709

jQuery is just a wrapper for native JavaScript functions. Anything you can do in jQuery you can do in JavaScript.

$( "someID" ).click( dummyCallback );

Boils down to:

document.getElementById("someID").addEventListener("click", dummyCallback, true);
// or the equivalent in older browsers

So how does the browser deal with event listeners on removed DOM elements? The simple answer is that it cleans them up, provided they are not otherwise referenced. You don't need to manually remove the event.

You can (accidentally or intentionally) keep a reference to either the DOM element (even if it is removed from the DOM) or the event handler. Keeping the reference will keep that code in memory.

It's useful to know that even if you keep a reference to the event handler, the DOM node can still be cleaned up, but the reverse is not true.

Upvotes: 1

Related Questions