Does remove a DOM object (in Javascript) will caus

2019-02-23 20:25发布

问题:

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.

回答1:

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.



回答2:

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.