【发布时间】:2011-07-11 18:53:14
【问题描述】:
我是 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;
}
不幸的是,删除会在 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>
memoryleaktest.js
test.msg = "loaded #"+loadCount;
test.data = "test data with 1MB size";
您可以通过将代码粘贴到两个文件中并打开 Testing.html 来重新创建内存泄漏。
我使用 Drip 来跟踪泄漏,在 Drip 中你可以看到内存不断增加并且“”没有被删除。
非常感谢您的帮助!
【问题讨论】:
-
第一个问题很好。欢迎来到 SO。
标签: javascript internet-explorer memory jsonp memory-leaks