Heim  >  Artikel  >  Web-Frontend  >  防止动态加载JavaScript引起的内存泄漏问题_javascript技巧

防止动态加载JavaScript引起的内存泄漏问题_javascript技巧

WBOY
WBOYOriginal
2016-05-16 18:45:12927Durchsuche

为了释放脚本资源,通常在返回后还要一些进行额外的处理。

复制代码 代码如下:

script = document.createElement('script');
script.src =
'http://example.com/cgi-bin/jsonp?q=What+is+the+meaning+of+life%3F';
script.id = 'JSONP';
script.type = 'text/javascript';
script.charset = 'utf-8';
// 标签加到head后,会自动加载并运行。
var head = document.getElementsByTagName('head')[0];
head.appendChild(script)

实际上很多流行的JS库都采用这种方式,创建一个scritp标签,赋予一个ID后加载脚本(比如YUI get()),加载完并回调后清除该标签。问题在于当你清除这些script标签的时候,浏览器仅仅是移除该标签结点。
复制代码 代码如下:

var script = document.getElementById('JSONP');
script.parentNode.removeChild(script);

当浏览器移除这标签结点后的同时并没对结点内JavaScript资源的进行垃圾回收,这意味着移除标签结点还不够,还得手动的清除script标签结点的内容:
复制代码 代码如下:

// Remove any old script tags.
var script;
while (script = document.getElementById('JSONP')) {
script.parentNode.removeChild(script);
// 浏览器不会回收这些属性所指向的对象.
//手动删除它以免内存泄漏.
for (var prop in script) {
delete script[prop];
}
}
Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn