Home » Jquery » javascript – How is memory handled when destroying DOM elements?-Exceptionshub

javascript – How is memory handled when destroying DOM elements?-Exceptionshub

Posted by: admin February 24, 2020 Leave a comment

Questions:

If I have click event listener on many dynamically created elements, will they use the memory when remove() is called by removeEventListner is not?

Say I have some code like this:

for (var i = 0; i < 9999; i++) {
  var $btn = $('<button class="my_button">');
  $('body').append($btn);
  $btn.click(function(){ /* ... */ })
}

$('.my_button').remove();

Will the event handlers still use memory? Do I have to call removeEventListner if I want to make sure there’s no memory leak risk?

How to&Answer:

The memory held by that element will be released when it is removed from the DOM and destroyed. This is handled by the browser, so although there in theory shouldn’t be any memory leaks you are at the mercy of the garbage collector.

That being said there’s a much better approach you can use here. Create a single delegated event handler on a parent element of all the buttons. Then you have one event handler instance which works for all button elements. This will save memory and mean you don’t need to worry about the specifics of any garbage collection when removing elements from the DOM. Try this:

$('#buttonContainer').on('click', '.my_button', function() {
  // button click action here...
});