解决IE6中元素插入顺序造成的内存泄漏

来源:互联网 发布:大学生找工作软件 编辑:程序博客网 时间:2024/06/04 18:59

下面是修改自微软的测试代码 点击MemoryFix后 Memory Leaking Insert也不会造成内存泄漏

 

</html>
    <head>
<script>
function MemoryFix(){
    var garbageBox=document.createElement("div");
    garbageBox.style.display="none";
    document.body.appendChild(garbageBox);
    var createElement=document.createElement;
    document.createElement=function(){
        var obj=Function.prototype.apply.apply(createElement,[document,arguments]);
        garbageBox.appendChild(obj);
        return obj;
    }
}
</script>
        <script language="JScript">
        function LeakMemory()
        {
            var hostElement = document.getElementById("hostElement");
            // Do it a lot, look at Task Manager for memory response
            for(i = 0; i < 5000; i++)
            {
                var parentDiv =
                    document.createElement("<div onClick='foo()'>");
                var childDiv =
                    document.createElement("<div onClick='foo()'>");
                // This will leak a temporary object
                parentDiv.appendChild(childDiv);
                hostElement.appendChild(parentDiv);
                hostElement.removeChild(parentDiv);
                parentDiv.removeChild(childDiv);
                parentDiv = null;
                childDiv = null;
            }
            hostElement = null;
        }

        function CleanMemory()
        {
            var hostElement = document.getElementById("hostElement");
            // Do it a lot, look at Task Manager for memory response
            for(i = 0; i < 5000; i++)
            {
                var parentDiv =
                    document.createElement("<div onClick='foo()'>");
                var childDiv =
                    document.createElement("<div onClick='foo()'>");
                // Changing the order is important, this won't leak
                hostElement.appendChild(parentDiv);
               parentDiv.appendChild(childDiv);
                hostElement.removeChild(parentDiv);
                parentDiv.removeChild(childDiv);
                parentDiv = null;
                childDiv = null;
            }
            hostElement = null;
        }
        </script>
    </head>
    <body>
        <button onclick="LeakMemory()">Memory Leaking Insert</button>
        <button onclick="CleanMemory()">Clean Insert</button>
        <button onclick="MemoryFix()">MemoryFix</button>
        <button onclick="CollectGarbage()">CollectGarbage</button>
        <div id="hostElement"></div>
    </body>
</html>

原创粉丝点击