在删除元素之前是否需要删除事件侦听器?
如果我有一个父元素,其子元素绑定了事件侦听器,那么在清除父元素之前是否需要删除这些事件侦听器? (即,parent.innerHTML = '';
)如果从 DOM 中删除元素后事件侦听器未与该元素解除绑定,是否会出现内存泄漏?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
只是为了更新这里的信息。我一直在测试各种浏览器,特别是针对 iframe onload 事件上的循环依赖事件侦听器的内存泄漏。
使用的代码(jsfiddle会干扰内存测试,因此请使用自己的服务器来测试):
如果没有内存泄漏,则测试运行后使用的内存将增加大约1000kb或更少。但如果出现内存泄漏,内存会增加约16,000kb。首先删除事件侦听器总是会导致较低的内存使用量(无泄漏)。
结果:
结论:
前沿应用程序可能可以通过不删除事件侦听器来逃脱惩罚。但尽管很烦人,我仍然认为这是一个很好的做法。
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.
简短回答:是
详细回答:大多数浏览器都会正确处理此问题并自行删除这些处理程序。有一些较旧的浏览器(IE 6 和 7,如果我没记错的话)会搞乱这个。是的,可能存在内存泄漏。您不必担心这一点,但您需要担心。请查看此文档。
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.