addEventListener memory leaks

我只是一个虾纸丫 提交于 2019-12-20 20:40:14

问题


When registering an event via addEventListener on an element, then delete that element without removing the event, and doing so repeatedly, would memory be "leaked"?


回答1:


It shouldn't leak. The one browser that's infamous for leaking like hell when an event handler causes a host-object<>JS-object loop is IE (up to version 7), and IE (up to version 8) doesn't support addEventListener.

Leave this running and see how the browser's memory usage is affected in the long term, if you want to test it in a particular browser.

<div id="x"></div>
<script type="text/javascript">
    function replace() {
        var x= document.getElementById('x');
        if (x.firstChild!==null)
            x.removeChild(x.firstChild);
        var el= document.createElement('p');
        el.addEventListener('click', click, false);
        x.appendChild(el);
    }
    function click() {
        alert('click');
    };
    setInterval(replace, 1);
</script>

(To test it with a reference loop present, move the function click definition up into the replace body.)




回答2:


You will get memory leak if you delete from DOM, elements that have attached listeners. But this only occurs in IE, Fx and others have advanced GC.

Often it happens, if you manipulate with DOM elements not via DOM, but like

el.innerHTML = ...

For example, YUI has custom realization setInnerHTML, to prevent memory leak in this case.



来源:https://stackoverflow.com/questions/2631265/addeventlistener-memory-leaks

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!