Do I need to remove event listeners before removing elements?

前端 未结 2 881
情深已故
情深已故 2020-11-29 00:29

If I have a parent element with children who have event listeners bound to them, do I need to remove those event listeners before I clear the parent? (i.e., parent.inn

2条回答
  •  独厮守ぢ
    2020-11-29 00:37

    Just to update the info here. I've been testing various browsers, specifically for memory leaks for circularly dependent event listeners on iframe onload events.

    The code used (jsfiddle interferes with memory testing, so use your own server to test this):

    
    

    If there is no memory leak, the used memory will increase by around 1000kb or less after the tests are run. However, if there is a memory leak, the memory will increase by about 16,000kb. Removing the event listener first always results in lower memory usage (no leaks).

    Results:

    • IE6 - memory leak
    • IE7 - memory leak
    • IE8 - no memory leak
    • IE9 - memory leak (???)
    • IE10 - memory leak (???)
    • IE11 - no memory leak
    • Edge (20) - no memory leak
    • Chrome (50) - no memory leak
    • Firefox (46) - hard to say, doesn't leak badly, so maybe just inefficient garbage collector? Finishes with an extra 4MB for no apparent reason.
    • Opera (36) - no memory leak
    • Safari (9) - no memory leak

    Conclusion: Bleeding edge applications can probably get away with not removing event listeners. But I'd still consider it good practice, in spite of the annoyance.

提交回复
热议问题