当前位置: 首页 > 图文教程 > 网络编程 > Javascript > 防止动态加载JavaScript引起的内存泄漏问题

Javascript
form中限制文本字节数js代码
use jscript with List Proxy Server Information
use jscript List Installed Software
List Installed Software Features
List Information About the Binary Files Used by an Application
List the Codec Files on a Computer
List the UTC Time on a Computer
List Installed Hot Fixes
excel操作之Add Data to a Spreadsheet Cell
Add Formatted Data to a Spreadsheet
Apply an AutoFormat to an Excel Spreadsheet
JavaScript语法着色引擎(demo及打包文件下载)
类之Prototype.js学习
一款JavaScript压缩工具:X2JSCompactor
iis6+javascript Add an Extension File
jscript之Open an Excel Spreadsheet
jscript之Read an Excel Spreadsheet
jscript之List Excel Color Values
去除图像或链接黑眼圈的两种方法总结
Add a Formatted Table to a Word Document

Javascript 中的 防止动态加载JavaScript引起的内存泄漏问题


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-10-10   浏览: 374 ::
收藏到网摘: n/a

利用Script标签可以跨域加载并运行一段JavaScript脚本, 但Neil Fraser先前已指出,脚本运行后资源并没被释放,即使是Script标签移除后。 为了释放脚本资源,通常在返回后还要一些进行额外的处理。
复制代码 代码如下:

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];
}
}