Recycle Image Object

When creating a new image element in javascript, the Google Chrome memory tool (developer tools> Timeline> Memory) naturally treats it as a new DOM element.

In my case, I get 1500+ DOM elements, and I want to get rid of them. I tried to save all the objects in an array and delete all of them in a loop when I am ready to create all the objects, which will lead to the following error:

Uncaught TypeError: Cannot call method 'removeChild' of null

This means that image objects are not displayed 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 any way to delete / delete / delete / delete image objects?

+7
source share
5 answers

Setting images = null will delete your link in the code for the object. However, to implement its load event, Chrome must have its own internal reference to the object.

That is, you may have this code:

 for( i = 0; i < urls.length; i++ ) { image = new Image(); image.src = urls[i]; image.onload = function(){alert('Test');}; image = null; } 

This way, you will still get many β€œTest” warnings, even if you don’t have a reference to these objects.

Therefore, I assume this is a bug in Chrome, not in your code.

Update: looking at the source of the Chromium source proves that (I mean the comment on lines 67-71 of this file, especially the FIXME note http://code.google.com/searchframe#OAMlx_jo-ck/src/third_party/WebKit/Source/ WebCore / bindings / v8 / custom / V8HTMLImageElementConstructor.cpp ):

 // Make sure the document is added to the DOM Node map. Otherwise, the HTMLImageElement instance // may end up being the only node in the map and get garbage-ccollected prematurely. // FIXME: The correct way to do this would be to make HTMLImageElement derive from // ActiveDOMObject and use its interface to keep its wrapper alive. Then we would // remove this code and the special case in isObservableThroughDOM. 
+9
source

If you do not add them to the DOM (for example, using appendChild for the parent), then removeChild useless. Image objects are only in memory.

And to place elements in memory, you only need to remove references to these objects (for example, set the reference variable to null), and garbage collection will do the rest. If you cannot reset them, they will not be GC'ed.

+6
source

AFAIK, setting null , should clear it: images[i] = null

+2
source

To get rid of the error described by the "naive" chrome and specilly IE and EDGE. You can change the image source to empty so that it occupies zero memory.

 image.src = ''; image = null; 
+2
source

I think the only way:

 for( i = 0; i < images.length; i++ ) images[i] = null; } // or just images = null; 
+1
source

All Articles