murvinlai
murvinlai

Reputation: 50375

Does remove a DOM object (in Javascript) will cause Memory leak if it has event attached?

So, if in the javascript, I create a DOM object in the HTML page, and attach event listener to the DOM object, upon I remove the the DOM from HTML page, does the event listener still exist and causing memory leak?

  function myTest() {
     var obj = document.createElement('div');
     obj.addEventListener('click', function() {alert('whatever'); });
     var body = document.getElementById('body'); // assume there is a <div id='body'></div> already
     body.appendChild(obj);
  }

  // then after some user actions. I call this:
  function emptyPage() {
    var body = document.getElementById('body');
    body.innerHTML = '';  //empty it.
  }

So, the DOM object, <div> inside body is gone. But what about the eventlistener? I'm just afraid that it will cause memory leak.

Upvotes: 4

Views: 1148

Answers (2)

Akidi
Akidi

Reputation: 935

The sad thing is, the W3C does not have an events collection where you can sift through all events applied to a single element. You could do it manually (i.e. obj.Events = {}; obj.Events[type] = []; obj.Events[type].push(fn) for each event that is added. Event[types] is an array so if you have multiple functions you wish to fire at a time, you can remove each individually), then loop through the obj.Events object to remove all events before removing the object.

Upvotes: 2

Luca Matteis
Luca Matteis

Reputation: 29267

JavaScript does garbage collection automatically for you.

It might free it right away or it might wait when the moment is best. This is up to the JavaScript implementation.

So no, it won't cause a memory leak.

Upvotes: 0

Related Questions