处理图像对象

Tim*_* S. 8 javascript image

在javascript中创建新的Image元素时,Google Chrome的内存工具(开发人员工具>时间轴>内存)自然会将其视为新的DOM元素.

在我的情况下,我最终得到了1500多个DOM元素,我希望摆脱它们.我已经尝试保存数组中的所有对象,并在我准备创建所有对象时在循环中删除所有对象,从而导致以下错误:

Uncaught TypeError: Cannot call method 'removeChild' of null

这表明Image对象没有出现在实际的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
}
Run Code Online (Sandbox Code Playgroud)

有没有办法删除/删除/取消设置/处置Image对象?

nai*_*sts 10

设置images = null会删除代码中对象的引用.但是,要实现其load事件,Chrome必须拥有自己的对象内部引用.

也就是说,您可以使用以下代码:

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

这样,即使您没有对这些对象的引用,您仍会获得大量"测试"警报.

因此,我猜测它是Chrome中的一个错误,而不是代码中的错误.

更新:查看Chromium源代码证明(我的意思是对此文件的第67-71行的评论,尤其是FIXME注释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.
Run Code Online (Sandbox Code Playgroud)

  • 这不是一个错误!您添加了一个侦听器,但没有将其删除.通过执行"image = null",您只需删除此具体引用.对象仍然存在于内存中,但不会留下任何引用.要让GS释放它,你必须通过"image.onload = null"删除事件 (2认同)

Jos*_*eph 6

如果你没有将它们添加到DOM(比如使用appendChild父级),那么removeChild就没用了.Image对象仅在内存中.

要在内存中处理项目,您只需要删除对这些对象的引用(比如将引用变量设置为null),垃圾收集将完成剩下的工作.如果你不能将它们全部归零,那么它们就不会被GC化.