我的 JavaSript 代码构建了一个 LI
元素列表。当我更新列表时,内存使用量会增加并且永远不会下降。我在 sIEve 中进行了测试,它表明浏览器保留了所有应该被 $.remove()
或 $.empty
jQuery 命令删除的元素。
我应该怎么做才能在不发生内存泄漏的情况下删除 DOM 节点?
参见 my other question具体代码。
最佳答案
DOM 保留所有 DOM 节点,即使它们已从 DOM 树本身中删除,删除这些节点的唯一方法是进行页面刷新(如果将列表放入 iframe,则不会刷新值得注意的)
否则,您可以等待问题变得严重到浏览器垃圾收集器被迫采取行动(在这里谈论数百兆字节的未使用节点)
最佳实践是重用节点。
编辑:试试这个:
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 = "";
}
}
要在您的上下文中使用它,您可以这样做:
discardElement(this);
关于javascript - 如何在没有内存泄漏的情况下删除 DOM 元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3785258/