您的位置:首页 > 其它

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

2009-03-07 21:50 204 查看
下面是修改自微软的测试代码 点击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>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: