I have a quick question regarding on adding/removing listeners of a DOM object. I would like to ask if the garbage collector be able to collect the memory when removing elements from the page.
Example: a <ul>
tag with a couple list of children(<li>
)
var ul = document.getElementById('someParent');
var children = ul.children;
var someFunction = function() {};
for(var i = 0; i < children.length; i++) {
children[i].addEventListener('click', someFunction);
}
// This is where I am not sure, would the garbage collector be able to collect
// the memory allocated on adding listener on children,
// if I remove the ul tag?
ul.remove();
The line ul.remove();
will remove ul
element and all of its children from the DOM. But memory for event listeners will not be released as long as you have references to those listeners, li
elements, and ul
element. Which you do have in variables children
, someFunction
and ul
.
If you want to let the garbage collector clean all of these, you can do for example:
ul.remove();
children = null;
someFunction = null;
ul = null;
That way variable children
will not hold the reference to those elements, and if you don't have any other variable in your code that hold the reference for those elements, garbage collector will collect them. The same holds for someFunction
. Note that ul
element holds all the references to its children and listeners, so ul
has to be cleaned as well.
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