Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dispose an image object

When creating a new Image element in javascript, Google Chrome's memory tool (Developer tools > Timeline > Memory) considers it as a new DOM element, naturally.

In my case, I'm ending up with 1500+ DOM elements, and I wish to get rid of them. I have tried to save all objects in an array and delete all of them in a loop when I'm ready creating all objects, resulting in the following error:

Uncaught TypeError: Cannot call method 'removeChild' of null

That indicates the Image objects doesn't appear in the actual DOM.

var images = [];
var i, image;

for( i = 0; i < urls.length; i++ ) {
    image = new Image();
    image.src = urls[i];
}

// other stuff happens

for( i = 0; i < images.length; i++ ) {
    // apparently this doesn't work because I'm not adding the image to my DOM
    // images[i].parentNode.removeChild( images[i] );

    // delete images
}

Is there a way to remove/delete/unset/dispose the Image objects?

like image 393
Tim S. Avatar asked Jun 14 '12 11:06

Tim S.


People also ask

What does Graphics dispose do?

Calling Dispose allows the resources used by this Graphics to be reallocated for other purposes.


2 Answers

If you are not adding them to the DOM (like using appendChild to a parent), then removeChild is useless. The Image objects are only in the memory.

And to dispose items in the memory, you only need to remove references to these objects (like set the referencing variable to null), and garbage collection will do the rest. If you can't null them all, they won't be GC'ed.

like image 99
Joseph Avatar answered Oct 13 '22 00:10

Joseph


To get rid of the bug described by "naivists" of chrome and specilly IE and EDGE. You can change the image source to empty so it take zero memory.

image.src = '';
image = null;
like image 26
Hicham Avatar answered Oct 13 '22 01:10

Hicham