If a DOM Element is removed, are its listeners also removed from memory?(如果移除了一个 DOM 元素,它的监听器是否也会从内存中移除?)
问题描述
If a DOM Element is removed, are its listeners removed from memory too?
Modern browsers
Plain JavaScript
If a DOM element which is removed is reference-free (no references pointing to it) then yes - the element itself is picked up by the garbage collector as well as any event handlers/listeners associated with it.
var a = document.createElement('div');
var b = document.createElement('p');
// Add event listeners to b etc...
a.appendChild(b);
a.removeChild(b);
b = null;
// A reference to 'b' no longer exists
// Therefore the element and any event listeners attached to it are removed.
However; if there are references that still point to said element, the element and its event listeners are retained in memory.
var a = document.createElement('div');
var b = document.createElement('p');
// Add event listeners to b etc...
a.appendChild(b);
a.removeChild(b);
// A reference to 'b' still exists
// Therefore the element and any associated event listeners are still retained.
jQuery
It would be fair to assume that the relevant methods in jQuery (such as remove()
) would function in the exact same way (considering remove()
was written using removeChild()
for example).
However, this isn't true; the jQuery library actually has an internal method (which is undocumented and in theory could be changed at any time) called cleanData()
(here is what this method looks like) which automatically cleans up all the data/events associated with an element upon removal from the DOM (be this via. remove()
, empty()
, html("")
etc).
Older browsers
Older browsers - specifically older versions of IE - are known to have memory leak issues due to event listeners keeping hold of references to the elements they were attached to.
If you want a more in-depth explanation of the causes, patterns and solutions used to fix legacy IE version memory leaks, I fully recommend you read this MSDN article on Understanding and Solving Internet Explorer Leak Patterns.
A few more articles relevant to this:
- JScript memory leaks
- Memory leaks in IE8
- JavaScript Memory Leaks
Manually removing the listeners yourself would probably be a good habit to get into in this case (only if the memory is that vital to your application and you are actually targeting such browsers).
这篇关于如果移除了一个 DOM 元素,它的监听器是否也会从内存中移除?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如果移除了一个 DOM 元素,它的监听器是否也会从内存中移除?
基础教程推荐
- 在for循环中使用setTimeout 2022-01-01
- 我什么时候应该在导入时使用方括号 2022-01-01
- 悬停时滑动输入并停留几秒钟 2022-01-01
- 响应更改 div 大小保持纵横比 2022-01-01
- 动态更新多个选择框 2022-01-01
- Karma-Jasmine:如何正确监视 Modal? 2022-01-01
- 当用户滚动离开时如何暂停 youtube 嵌入 2022-01-01
- 在 JS 中获取客户端时区(不是 GMT 偏移量) 2022-01-01
- 有没有办法使用OpenLayers更改OpenStreetMap中某些要素 2022-09-06
- 角度Apollo设置WatchQuery结果为可用变量 2022-01-01