Removing a <script> element just removes the script's *source code* from the
DOM. It doesn't undo any actions that the script has already performed, such
as defining functions or variables or creating other DOM elements. It
doesn't change their availability for garbage collection at all.

In your example, the hello function will never be garbage collected, because
the window object has a property named 'hello' that holds a reference to the
function.

As Ami mentioned you can null out that window.hello property or use the
delete operator on it, or better, use the (function() { /* code here */
})(); wrapper to avoid setting global properties.

-Mike

On Wed, Jan 13, 2010 at 2:40 PM, Nathan Klatt <n8kl...@gmail.com> wrote:

> On Wed, Jan 13, 2010 at 1:53 PM, nihal <nihal.c...@gmail.com> wrote:
> > is there anyway to remove the newly added function from the dom?
>
> Wrap the code you want to be removeable in its own <script> element,
> give it an id, then remove it just like any other element. As has been
> discussed today, removing it doesn't mean *poof* it's gone, just that
> it could be removed by the garbage collector, so you'll likely be able
> to continue calling the function after it's been removed.  See:
>
> http://jsbin.com/ixite/edit
>
> <script id="removeMe" type="text/javascript">
>  function hello(msg) { alert(msg); }
> </script>
>
> <script type="text/javascript">
> $().ready(function() {
>  hello("one");
>  $("#removeMe").remove();
>  hello("two");
>  setTimeout("hello('three')", 2500);
> });
> </script>
>
> The code gets removed from the DOM (verified using Firebug) but the
> function still works 2.5 seconds later.
>
> Nathan
>

Reply via email to