如何从DOM中卸载包含其所有已定义对象的JavaScript资源?
我开发了一个简单的框架,可以将html片段加载到"主"html中.每个片段都是自包含的,可能包含对其他JS和CSS文件的引用.解析JS和CSS资源并将其动态添加到html中.当从DOM中删除/替换片段时,我想删除它的JS和CSS.
如果我删除了下面示例中的script元素,则page1.js中定义的函数仍然可用.
<html>
<head>
<script src="page1.js" type="text/javascript"></script>
</head>
<body>
...
Run Code Online (Sandbox Code Playgroud)
有没有办法从DOM卸载page1.js对象?
=========我使用的测试代码=======
我尝试了下面评论中的建议; 使用清理功能删除添加的对象 - 但即使这样也会失败.我用于测试的来源:
<html>
<head>
<script type="text/javascript">
function loadJSFile(){
var scriptTag = document.createElement("script");
scriptTag.setAttribute("type", "text/javascript");
scriptTag.setAttribute("src", "simple.js");
var head = document.getElementsByTagName("head")[0];
head.appendChild(scriptTag);
}
function unloadJSFile(){
delete window.foo;
delete window.cleanup;
alert("cleanedup. typeof window.foo is " + (typeof window.foo));
}
</script>
</head>
<body>
Hello JavaScript Delete
<br/>
<button onclick="loadJSFile();">Click to load JS</button>
<br/>
<button onclick="foo();">call foo()</button>
<br/>
<button onclick="unloadJSFile();">Click to unload JS</button>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
simple.js来源:
var foo = function(){
alert("hello from foo");
}
Run Code Online (Sandbox Code Playgroud)
cdh*_*wie 15
这是不可能做到的.
执行脚本时,会将函数定义添加到全局window对象中.可能存在附加到函数的调试符号,用于指示函数的来源,但脚本无法使用此信息.
关于你可以实现这样的事情的唯一方法是在脚本中创建一个伪命名空间,然后在完成后抛弃整个命名空间.但是,这个问题告诉我你正试图以错误的方式做某事.也许详细阐述您的场景将有助于我们提供替代解决方案.
不,那是不可能的.您可以构建一个简单的清理函数,删除该文件中定义的所有变量:
var foo = 'bar';
var cleanup = function () {
delete window.foo;
delete window.cleanup;
};
// unload all resources
cleanup();
Run Code Online (Sandbox Code Playgroud)
另一种方法是为您的碎片使用模块化对象结构,然后自行清理.这涉及稍高的开销但可能是值得的,因为它使代码更容易阅读和维护:
// creates the object using the second parameter as prototype.
// .create() is used as constructor
GlobalModuleHandlerThingy.addModule('my_module', {
create: function () {
this.foo = 'bar';
return this;
},
foo: null,
destroy: function () {
// unload events, etc.
}
});
GlobalModuleHandlerThingy.getModule('my_module').foo; // => bar
GlobalModuleHandlerThingy.unloadModule('my_module'); // calls .destroy() on the module and removes it.
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
29258 次 |
| 最近记录: |