Why do scripts still run after their tags get removed?
I was testing jQuery to remove style and link tags to remove CSS styles when i accidentally typed ‘script’ instead of ‘style’ for the selector. But what happened is that the scripts defined in those tags still run. Why is that?
//assume foo is defined
foo();
var scripts = Array.prototype.slice.call(document.getElementsByTagName('script')),
current;
//remove all scripts
while (scripts.length) {
current = scripts.pop();
current.parentNode.removeChild(current);
}
//foo still works
foo();
foo();
$('script').remove();
foo();
And a side question: If they don’t get removed this way, what will?
They run because they are loaded into memory when the script is first parsed.
You can set anything to
undefinedto disable it.