views:

114

answers:

2

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.

+8  A: 

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.

Matt
I see. Do you know if there is a way to interact directly with the javascript engine in order to remove unwanted objects / variables etc. in such a case?
DKinzer
@DKinzer - Most browsers include a console for direct interaction. You can usually bring this up with `F12` or `Ctrl+Shift+J`. Of course, due to scoping, you can only modify variables within the global (`window`) scope.
Matt
+2  A: 

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;-).

Alex Martelli
To be frank, that doesn't come as a surprise to me. I just referred to the discrepancy between RFC 4329 and browser reality regarding `text/javascript` vs. `application/javascript`
Marcel Korpel