jQuery 1.5 IE8中的内存泄漏 [英] jQuery 1.5 Memory leak in IE8

查看:229
本文介绍了jQuery 1.5 IE8中的内存泄漏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我相信我可能在最新版本的jQuery中发现了一个相当简单的漏洞。

I believe I may have found a fairly simple leak in the latest release of jQuery.

var  listen = function(){};
var testLeak = function(){
    for(var i = 0; i<100; i++){
        var item = {};
        item.elem = $(document.createElement('div'));
        item.addListener = function(name,listener){
            var self = this;
            var wrappedListener = function(){
                return listener.apply(self,arguments);
            }
            this.elem.bind(name, wrappedListener);
            wrappedListener = null;
        }
        item.addListener('eventName',listen );
        item.elem.unbind();
        item.elem.remove();  //with this un-commented, the loop leaks
        // item.elem = null; //with this also un-commented, the leak dissapears
    }
};

$(document).ready(function(){
    setInterval(testLeak, 100);
}

我在jsfiddle上创建了一个项目来证明这一点:

I have created a project on jsfiddle that demonstrates this:

http://jsfiddle.net/rJ8x5/8/

重要的是要注意如果我调用.remove(),这不会泄漏,如果我调用.remove()但是将.elem引用设置为null,它也不会泄漏。它是虽然jQuery在调用.remove()时持有对item的引用,但是反过来,它持有对.elem的引用。
有什么想法吗?
正如你所看到的,我已经将wrappedListener设置为null试图阻止任何无意的关闭,但这没有帮助。

It is important to note that if I do not call .remove(), this does not leak, and if I do call .remove() but set the .elem reference to null, it also does not leak. It is as though jQuery is holding a reference to item when I call .remove() which, in-turn, holds a reference to .elem. Any thoughts? As you can see, I have set the wrappedListener to null in an attempt to prevent any inadvertent closures, but this does not help.

编辑:我更新了jsfiddle脚本以实际将节点添加到DOM。这样做 not 影响行为

I updated the jsfiddle script to actually add the node to the DOM. This does not affect behavior

EDIT2:已找到问题的解决方案,但我仍然不清楚为什么这个脚本w只有在包含对remove()的调用时才会泄漏。仍然希望得到答案...

So a solution to the problem has been found, but it is still not clear to me why this script will leak only when you include the call to remove(). Still hoping for an answer...

推荐答案

如果基于闭包的内存泄漏(原样)我的例子是var item = {};),detachevent不会发出javascript / DOM循环引用已被破坏的信号。您必须手动清空对元素的引用。为什么调用remove()似乎让事情进入这种状态从未确定

Turns out, if a closure-based memory leak is made (as it is in my example with "var item = {};"), detachevent will not signal that the javascript/DOM circular reference has been broken. You HAVE to null the reference to the element manually. Why the call to remove() seems to get things into this state was never determined

这篇关于jQuery 1.5 IE8中的内存泄漏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆