How to remove DOM elements without memory leaks?

前端 未结 5 1703
無奈伤痛
無奈伤痛 2020-11-28 21:29

My JavaSript code builds a list of LI elements. When I update the list, memory usage grows and never goes down. I tested in sIEve and it shows that the browser

相关标签:
5条回答
  • 2020-11-28 21:47

    This is more of an FYI than an actual answer, but it is also quite interesting.

    From the W3C DOM core specification (http://www.w3.org/TR/DOM-Level-2-Core/core.html):

    The Core DOM APIs are designed to be compatible with a wide range of languages, including both general-user scripting languages and the more challenging languages used mostly by professional programmers. Thus, the DOM APIs need to operate across a variety of memory management philosophies, from language bindings that do not expose memory management to the user at all, through those (notably Java) that provide explicit constructors but provide an automatic garbage collection mechanism to automatically reclaim unused memory, to those (especially C/C++) that generally require the programmer to explicitly allocate object memory, track where it is used, and explicitly free it for re-use. To ensure a consistent API across these platforms, the DOM does not address memory management issues at all, but instead leaves these for the implementation. Neither of the explicit language bindings defined by the DOM API (for ECMAScript and Java) require any memory management methods, but DOM bindings for other languages (especially C or C++) may require such support. These extensions will be the responsibility of those adapting the DOM API to a specific language, not the DOM Working Group.

    In other words: memory management is left to the implementation of the DOM specification in various languages. You would have to look into the documentation of the DOM implementation in javascript to find out any method to remove a DOM object from memory, which is not a hack. (There is however very little information on the MDC site on that topic.)


    As a note on jQuery#remove and jQuery#empty: from what I can tell neither of these methods does anything other than removing Objects from DOM nodes or removing DOM nodes from the document. They only remove That of course does not mean that there is no memory allocated to these objects (even though they aren't in the document anymore).

    Edit: The above passage was superfluous since obviously jQuery cannot do wonders and work around the DOM implementation of the used browser.

    0 讨论(0)
  • 2020-11-28 21:51

    Have you removed any event listeners? That can cause memory leaks.

    0 讨论(0)
  • 2020-11-28 21:56

    The DOM preserves all DOM nodes, even if they have been removed from the DOM tree itself, the only way to remove these nodes is to do a page refresh (if you put the list into an iframe the refresh won't be as noticable)

    Otherwise, you could wait for the problem to get bad enough that the browsers garbage collector is forced into action (talking hundreds of megabytes of unused nodes here)

    Best practice is to reuse nodes.

    EDIT: Try this:

    var garbageBin;
    window.onload = function ()
        {
        if (typeof(garbageBin) === 'undefined')
            {
            //Here we are creating a 'garbage bin' object to temporarily 
            //store elements that are to be discarded
            garbageBin = document.createElement('div');
            garbageBin.style.display = 'none'; //Make sure it is not displayed
            document.body.appendChild(garbageBin);
            }
        function discardElement(element)
            {
            //The way this works is due to the phenomenon whereby child nodes
            //of an object with it's innerHTML emptied are removed from memory
    
            //Move the element to the garbage bin element
            garbageBin.appendChild(element);
            //Empty the garbage bin
            garbageBin.innerHTML = "";
            }
        }
    

    To use it in your context, you would do it like this:

    discardElement(this);
    
    0 讨论(0)
  • 2020-11-28 21:56

    The code below does not leak on my IE7 and other browsers:

    <html>
    <head></head>
    <body>
        <a href="javascript:" onclick="addRemove(this)">add</a>
        <ul></ul>
        <script>
            function addRemove(a) {
                var ul = document.getElementsByTagName('UL')[0],
                    li, i = 20000;
                if (a.innerHTML === 'add') {
                    while (i--) {
                        li = document.createElement('LI');
                        ul.appendChild(li);
                        li.innerHTML = i;
                        li.onclick = function() {
                            alert(this.innerHTML);
                        };
                    }
                    a.innerHTML = 'remove';
                } else {
                    while (ul.firstChild) {
                        ul.removeChild(ul.firstChild);
                    }
                    a.innerHTML = 'add';
                }
            }
        </script>
        </body>
    </html>
    

    May be you can try to spot some differences with your code.
    I know that IE leaks far less when you insert first the node in the DOM before doing anything to it, eg: attaching events to it or filling its innerHTML property.

    0 讨论(0)
  • 2020-11-28 21:59

    If you have to "post-fix" leakage, and must do so without rewriting all your code to take closures, circular references etc in account, use Douglas Crockfords Purge-method prior to delete:

    https://crockford.com/javascript/memory/leak.html

    Or use this closure-fix workaround:

    Leak Free Javascript Closures

    0 讨论(0)
提交回复
热议问题