Remove dom does not call removeEventListener

const addDOM = () => {
  const div = document.createElement("div")
  div.addEventListener("click", e => {})
  document.body.appendChild(div)
  div.remove()
}

let i = 99999999
while(i-- > 0) {
  addDOM()
}

will it be bad if I don"t call removeEventListener to remove the event listener of click before removing a dom node?

Mar.25,2021

as far as the code you give is concerned, it will not matter. After checking the, remove children with the chrome memery tool, the number of EventListener objects will be reduced.

The reason why the example of jzoom upstairs runs well makes you feel that Listener does not have automatic gc, because its div is a global variable, so even if it is removed from dom tree, the div object still exists on global and is referenced by global. The gc mechanism naturally does not clean up its listener, but the scope of your div is in the function of addDom, so once 999999 div are removed from dom tree, no object references them. The listener on their bodies will also be automatically gc.


the main test code


const handle = e => { console.log('click event!') };
const div = document.createElement('div')
div.addEventListener('click', handle)
document.body.appendChild(div)
div.dispatchEvent(new Event('click'));
div.remove()
div.dispatchEvent(new Event('click'));
div.removeEventListener('click', handle);
div.dispatchEvent(new Event('click'));

after calling remove, you can still output using dispatchEvent, indicating that Listener has not been removed with remove. Be sure to call removeEventListener manually. So the conclusion is that it will have an impact.

clipboard.png

MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1e9b4d2-4ed15.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1e9b4d2-4ed15.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?