Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is the javaScript not part of the DOM?

Why is it that scripts can still function even after the code used to create them is removed from the DOM?

I ran into a situation where I wanted to prevent a broken script from running (@see my post).

In my attempt to come up with a solution I wrote an extension with the following line (just to see what would happen).

$('script', doc).remove();
/*doc is passed here because this script is running as a firefox extension 
  outside of the document context.*/

I assumed that this would remove all the scripts from the DOM, which it did, and that therefore no scripts would run on the page, which is not the case.

I would love to know more about what's behind this behavior.

like image 538
dkinzer Avatar asked Dec 28 '22 18:12

dkinzer


2 Answers

The script is part of the DOM, sure, but the result of that script executing is left up to the javascript engine. Removing a script's source (the part that's in the DOM) will not remove existing varibles in the engine's memory.

like image 87
Matt Avatar answered Dec 31 '22 09:12

Matt


It is correct that Javascript is not part of the DOM (and vice versa). Indeed, at a recent ACM Connections/Reflections conference I was an invited speaker, another one was Javascript guru Douglas Crockford, and we had interesting chats -- I was astonished to learn from him that the committee that works on standardizing the DOM (in the w3c) and the one that works on standardizing Javascript (in ECMA) have no overlap, no coordination, and are in fact hardly aware of each other's existence and work (but apparently no more astonished than Crockford himself had been upon learning this peculiar fact;-).

like image 26
Alex Martelli Avatar answered Dec 31 '22 07:12

Alex Martelli