1

if we register an event handler like this:

$(div1).on('event', handler ...

and after div1 gets removed (not by jQuery), but using plain js,

does the handler stay orphaned in memory ?

buga
  • 852
  • 9
  • 21
  • 2
    As long as the removed element is not garbage collected from the memory, the event listener stays. If the handler function itself is declared or stored in a variable, it will not be removed from the memory as long as there's a reference to the function. – Teemu Sep 26 '22 at 10:33
  • @Teemu so jQuery doesn't hold any references to this handler, and it could get GC after a few seconds ? – buga Sep 26 '22 at 10:36
  • I suppose jQuery keeps a reference, that's why it's recommended to remove all jQuery related elements with jQuery methods. – Teemu Sep 26 '22 at 10:37
  • @Teemu so, if it holds a reference, that means it will never get GC, it's not using anything like `MutationObserver` to remove these references – buga Sep 26 '22 at 10:39
  • @buga Well jQuery does hold a reference to the control, so it will also hold onto this until that goes out of scope too. eg. `var x = $('.control')`, If `x` had say been used inside a `setInterval` that you never clear, this will stay in memory. Basically as long as any references to the event, element no longer exist, then it should free the memory. – Keith Sep 26 '22 at 10:40
  • Old versions didn't use Mutation Observer, I'm not sure if newer are. I doubt that, though, as Mutation Observers are slowing page down. – Teemu Sep 26 '22 at 10:40
  • And unless there is some bug with `jquery` it shouldn't even be needed. – Keith Sep 26 '22 at 10:46
  • SImilar question: [If a DOM Element is removed, are its listeners also removed from memory?](https://stackoverflow.com/questions/12528049/if-a-dom-element-is-removed-are-its-listeners-also-removed-from-memory) – user2314737 Sep 26 '22 at 10:58

0 Answers0