如何清理Internet Exploreor中的JSONP内存

zyz*_*yis 6 javascript memory internet-explorer jsonp memory-leaks

我是JSONP开发的新手,我发现IE 7/8不会清理JSONP脚本占用的内存.运行几个小时后,这会在我的页面中导致非常高的内存消耗.

我浏览了互联网,发现大多数修复都是基于Neil Fraser的提示.从博客中可以看出,您需要使用类似的代码删除脚本中的所有属性

    var tmp;
    while (tmp = document.getElementById('JSONP')) {
        tmp.parentNode.removeChild(tmp);

        // this deletion will create error in IE.
        for (var prop in tmp) delete tmp[prop];
        tmp = null;
    }
Run Code Online (Sandbox Code Playgroud)

不幸的是,删除将在IE中创建"对象不支持此操作"的错误,并且它不会释放内存.

所以我的问题是如何真正释放我的JSONP脚本的内存?

我把我的测试代码如下:

Testing.html

<html><head></head><body><script>
var script,
head = document.getElementsByTagName('head')[0],
loadCount= 0,
uuid= 1,
URL= "memleaktest.js?uuid=",

clearConsole = function() {
    var con= document.getElementById("console");
    while (con.childNodes.length) 
        con.removeChild(con.childNodes[0]);
},

log = function(msg) {
    var div= document.createElement("DIV"),
        text= document.createTextNode(msg),
        con= document.getElementById("console");

    div.appendChild(text);
    con.appendChild(div);
},

test = { "msg" : null, "data" : null };

var loaded= function() {
    if (!test.msg) 
        return setTimeout(loaded,10);

    log("loaded #" + loadCount + ": " + test.msg);

    var tmp;
    while (tmp = document.getElementById('JSONP')) {
        tmp.parentNode.removeChild(tmp);

        // not working in IE 7/8
        // for (var prop in tmp) delete tmp[prop];
        tmp = null;
    }

    test.msg = test.data = null;

    if (--loadCount) 
        setTimeout(load, 100);
};

var load = function(){
    var url= URL + (uuid ++);
    log("load via JSONP: "+url);

    script= document.createElement('script');       
    script.id = 'JSONP';
    script.type = 'text/javascript';
    script.charset = 'utf-8';
    script.src = url;
    head.appendChild(script);
    setTimeout(loaded,1000);
};
</script>
<div>
<button onclick="loadCount=3; load();" name="asd" value="asdas">jsonp load</button>
<button onclick="clearConsole();" name="asd" value="asdas">clear Console</button>
</div>
<div id="console"></div>
</body></html>
Run Code Online (Sandbox Code Playgroud)

memoryleaktest.js

test.msg = "loaded #"+loadCount;
test.data = "test data with 1MB size";
Run Code Online (Sandbox Code Playgroud)

您可以通过将代码粘贴到两个文件中来重新创建内存泄漏并打开Testing.html.

我使用Drip来跟踪泄漏,在Drip中你可以看到内存不断增加,并且"<"脚本">"不会被删除.

非常感谢您的帮助!

Nei*_*ser 2

您的问题已在您链接的博客文章中得到解答。请参阅最后一段。

与往常一样,IE 是一种奇怪的浏览器,需要特殊的情况。IE 不喜欢删除 DOM 节点的本机属性。幸运的是,这并不重要,因为 IE 允许重复使用脚本标签。只需更改 SRC 属性,它就会立即获取新页面。因此,在 IE 中只需要一个脚本标签。

提供的代码适用于除 IE 之外的所有浏览器,并且在 IE 中这不是问题,因为您只需更改脚本标记的 src 属性,它就会重新触发。所以你的代码(仅适用于 IE)将是:

var script = document.getElementById('JSONP');
if (!script) {
  [create it once]
}
script.src = URL + (uuid ++);
Run Code Online (Sandbox Code Playgroud)