From: Mike Harrison on
Hi, I've got a question regarding garbage collection of image objects
that are assigned to a local variable.

Is it safe to write code like below? This code assigns a new image to
a local variable and sets an onload handler, which gets called after
the variable has gone out of scope.

The handler always seems to get called even though there are no
remaining references to the object, so I wondered at what point the
image gets marked for garbage collection?

Is there a chance it could be deleted before the load handler is
called?

<script type="text/javascript">

function ImageLoaded(e)
{
alert ("Image loaded");
}

function LoadImage()
{
var img = document.createElement ("img");
img.addEventListener ("load", ImageLoaded, false);
img.src = "image.jpg";
}

LoadImage();

</script>
From: Thomas 'PointedEars' Lahn on
Mike Harrison wrote:

> Is it safe to write code like below?
> [...]
> function ImageLoaded(e)
> {
> alert ("Image loaded");
> }
>
> function LoadImage()
> {
> var img = document.createElement ("img");
> img.addEventListener ("load", ImageLoaded, false);
> img.src = "image.jpg";
> }
>
> LoadImage();

Very likely, yes. In particular, it is good in that it avoids the problem
of circular references involving DOM objects which would cause memory leaks
in MSHTML.

However, it does not make sense.

> This code assigns a new image to a local variable and sets an onload
> handler, which gets called after the variable has gone out of scope.

That is why it avoids the problem described above.

> The handler always seems to get called even though there are no
> remaining references to the object,

There is very likely still a reference to the object in the DOM
implementation's event registry.

> so I wondered at what point the image gets marked for garbage collection?

Very likely not before the event listener was called.

> Is there a chance it could be deleted before the load handler is
> called?

Only a very small one. It does not make sense to garbage-collect an object
that you have just added an event listener for.


PointedEars
--
Prototype.js was written by people who don't know javascript for people
who don't know javascript. People who don't know javascript are not
the best source of advice on designing systems that use javascript.
-- Richard Cornford, cljs, <f806at$ail$1$8300dec7(a)news.demon.co.uk>