开发者

Several events and memory leak

I create several elements with attached events and delete them with "innerHTML = ''". The elements are out, but what about the events ? Are they erased as well ?

<script type = "text/javascript">
    window.onload = function () {
        var container = document.createElement ("div");
            container.style.marginTop = "20px";

        var erase = document.createElement ("input");
            erase.setAttribute ("type", "button");
            erase.value = "Erase inputs";

        var insert = document.createElement ("input");
            insert.setAttribute ("type", "button");
            insert.value = "Insert inputs";

        document.开发者_运维问答body.appendChild (insert);
        document.body.appendChild (erase);
        document.body.appendChild (container);

        erase.onclick = function () {
            if (container.innerHTML !== "") {
                container.innerHTML = "";

                alert ("innerHTML = \"\". What about the events ?")
            }
        }

        insert.onclick = function () {
            for (var i = 0; i < 1000; i ++) {
                var input = document.createElement ("input");
                    input.setAttribute ("type", "button");
                    input.value = "Click Me !";

                input.onclick = function () {
                    alert ("STOP ! Hammer time :)")
                }

                container.appendChild (input);
            }
        }
    }
</script>

Possible memory leak ?

Thanks.


No - to be safe, set your "onclick" attributes to null before you blow away the contents.

    erase.onclick = function () {
        if (container.innerHTML !== "") {
            var inps = container.getElementsByTagName('input');
            for (var inpi = 0; inpi < inps.length; ++inpi)
              inps[i].onclick = null; // also "onchange", "onblur", anything else

            container.innerHTML = "";

            alert ("innerHTML = \"\". What about the events ?")
        }
    }

The DOM node garbage collector in Internet Explorer doesn't know what to do with JavaScript garbage, so it's lost. (It may well be the case that DOM nodes dangling off free JavaScript objects are similarly ignored; I can't recall exactly.)

Each one of those event handlers will have a reference to the closures formed by the outer "onload" handler and by the "onclick" handler of the "insert" control. They'll all be sharing a reference, so in this particular case I don't think it'd be that much memory. If, however, you set up each of those 1000 event handlers via another function, then there'd be that much more leakage.

I hate to say this, but one of the conveniences of using a framework is that a lot (not all but a lot) of this sort of thing is taken care of for you.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜