Reputation: 1884
I am appending a child element with a reference to at javascript and a stylesheet, but I would like to delete it again when there is no use of it anymore.
var head = document.getElementsByTagName('head')[0];
// We create the style
var style = document.createElement('link');
style.setAttribute("rel", "stylesheet");
style.setAttribute("type", "text/css");
style.setAttribute("href", '_css/style.'+app+'.css');
var script = document.createElement('script');
script.setAttribute("type", "text/javascript");
script.setAttribute("src", '_scripts/_js/script.'+app+'.js');
// And the append the style
head.appendChild(style);
head.appendChild(script);
This is how I append the scripts and it works perfectly.. But I can't figure out how to delete the tags again from the head tag in HTML.
Does anybody know how to remove the tags from the header tag again.. I have been searching all around Stackoverflow but nobody actually seem to have this kind of problem, but if anybody knows there is another question answering this, please tell me..
Upvotes: 3
Views: 10729
Reputation: 119847
You can remove elements using removeChild
:
var head = document.getElementsByTagName('head')[0];
//removing them from the head, where you added them
head.removeChild(script);
head.removeChild(style);
However:
Thus removing style/link elements might have some use, but there is no use removing script elements.
Upvotes: 3
Reputation: 10880
In short, You Cant, Even if you remove the scripts
tags, those scripts are in the memory and there is no remove them.
One hack is to write a script that identifies what the other scripts are doing (adding events, creating variables, functions etc)and then neutralize them
But the real way to solve this problem is to write your scripts in a closure,so that they are removed from the memory as soon as the program control is out of their scope.
You might also want to dig into Require.js
Upvotes: 6
Reputation: 48972
I'm afraid we cannot remove script tags. Even if you remove it, the script has already been executed and cannot be undo.
For example: in test.js file
window.Test = "aaa";
When we reference this script, the browser will download and automatically execute all the statements in the file. When we remove the script tag, the statements have been executed (window variable already has the property Test)
Upvotes: 1
Reputation: 4859
document.getElementsByTagName('head')[0].removeChild(document.getElementsByTagName('head')[0].getElementsByTagName('script')[0]);
Upvotes: 0