且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在chrome dev工具中查找JS内存泄漏

更新时间:2023-02-27 15:11:44

这些元素在代码中被引用,但它们与页面的主DOM树断开连接。

Those elements are being referenced in your code but they are disconnected from the page's main DOM tree.

简单示例:

var a = document.createElement("div");

a 现在引用断开连接的元素,它当 a 仍在范围内时,无法进行GC。

a references a disconnected element now, it cannot be GC'd when a is still in scope.

如果分离的dom树在内存中持续存在,那么你正在保持对它们的引用。使用jQuery这样做有点容易,
只保存对遍历结果的引用并保留它。例如:

If the detached dom trees persist in memory then you are keeping references to them. It is somewhat easy with jQuery to do this, just save a reference to a traversed result and keep that around. For example:

var parents = $("span").parent("div");
$("span").remove();

现在引用了跨距,即使看起来你无论如何都没有引用它们。 parents 通过jQuery .prevObject 属性间接保留对所有跨度的引用
。所以做 parents.prevObject 会给出引用所有跨度的对象。

Now the spans are referenced even though it doesn't appear you are referencing them anyhow. parents indirectly keeps references to all the spans through the jQuery .prevObject property. So doing parents.prevObject would give the object that references all the spans.

参见这里的示例 http://jsfiddle.net/C5xCR/6/ 。即使直接看起来不会引用跨度,但是
它们实际上是由 parents 全局变量引用的,你可以看到1000个跨度分离的DOM树永远不会消失。

See example here http://jsfiddle.net/C5xCR/6/. Even though it doesn't directly appear that the spans would be referenced, they are in fact referenced by the parents global variable and you can see the 1000 spans in the Detached DOM tree never go away.

现在这里是相同的jsfiddle但是:

Now here's the same jsfiddle but with:

delete parents.prevObject

你可以看到跨度不再是分离的dom树,或任何地方。 http://jsfiddle.net/C5xCR/7/

And you can see the spans are no longer in the detached dom tree, or anywhere for that matter. http://jsfiddle.net/C5xCR/7/