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.innerHTML = '';
) Could there be memory leaks if event listeners are not unbound from an element if it's removed from the DOM?
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- void before promise syntax
- Keeping track of variable instances
- Can php detect if javascript is on or not?
Short answer: yes
Long answer: Most browsers handle this correctly and remove those handlers themselves. There are some older browsers (IE 6 and 7, if i recall correctly) that are messing this up. Yes, there could be memory leaks. You should not have to worry about this, but you need to. Have a look at this document.
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:
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.