如何从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 = …
Run Code Online (Sandbox Code Playgroud) 我正在开发一个将由第三方开发人员使用的JavaScript库.API包含具有此签名的方法:
function doSomething(arg1,arg2,options)
您是否建议验证: - 参数类型是否有效? - 选项属性是否正确?例如:开发人员没有错误地通过onSucces而不是onSuccess?