Does a DOM object (in Javascript) remove a memory leak if it is associated with an event?

So, if in javascript I create a DOM object on an HTML page and attach an event listener to the DOM object, after removing the DOM from the HTML page, does the event listener still exist and cause a 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, the <div> inside the body disappeared. But what about an eventlistener ? I am just afraid that this will cause a memory leak.

+4
source share
2 answers

The sad thing is that the W3C does not have an event collection where you can sift through all the events that apply to a single item. You can do this manually (ie obj.Events = {}; obj.Events [type] = []; obj.Events [type] .push (fn) for each added event. The [types] event is an array , so if you have several functions that you want to run at the same time, you can delete them separately), and then scroll through the obj.Events object to delete all events before deleting the object.

+2
source

JavaScript does garbage collection automatically for you.

He can free him right away, or he can wait for it to be better. It depends on the implementation of JavaScript.

No, this will not cause a memory leak.

0
source

Source: https://habr.com/ru/post/1312175/


All Articles