Reputation: 29
I want to unload a specific script(example.js) on my html page dynamically, which I can do by
var elem = document.getElementById("scid");
elem.parentElement.removeChild(elem);
where scid is the script id
but stll the elements of the script remain , as the script once executed leaves its attributes even after removing the tag.
Is there any way to completely remove the javascript with all its elements and attributes?
Upvotes: 2
Views: 849
Reputation: 91
The examples given still return style and script text NOT just the text of the web page. Try this:
function funcTextOnlyFromHTML(thedocument){
var varArrScripts = thedocument.getElementsByTagName("script");
for(var i = 0; i < varArrScripts.length; i++){
varArrScripts[i].innerText = "";
}
var varArrStyles = thedocument.getElementsByTagName("style");
for(var i = 0; i < varArrStyles.length; i++){
varArrStyles[i].innerText = "";
}
return thedocument.body.innerText;
}
Upvotes: 0
Reputation: 1188
You could define a way to ask the javascript code to destruct itself from the javascript and dom env.
A sample could be:
<script>
var sample = {
destroy:function(){/*no matter what it has to clean*/}
};
</script>
then in another piece of code:
sample.destroy();
Upvotes: 0
Reputation: 13713
I would recommend trying using something like RequiredJs (http://requirejs.org/) - which such library you can dynamically load javascript code, in the form of modules. Since that module is an object, once you don't need it you can dispose of it.
It has more advantages, such as caching, lazy-loading scripts... I suggest to see if it suits you needs.
Upvotes: 0
Reputation: 1074138
As you've found, once the script has run, the things it defines are part of the JavaScript environment (and possibly the DOM, if the code creates and adds DOM elements). That code is not connected to the script
element (which can be removed without affecting it).
There is no simple way. You have to find out what the script does and then undo those things individually. For instance, if the script creates global functions foo
and bar
, hooks the resize
event on window
, and creates new elements on the page, you have to set foo
and bar
to undefined
, remove the resize
handler (which may be tricky, if you don't have a reference to the function they used to hook it), and remove the new elements on the page.
Upvotes: 3