处理图像对象

时间:2012-06-14 11:21:43

标签: javascript image

在javascript中创建新的Image元素时,Google Chrome的内存工具(开发人员工具> Timeline> Memory)自然会将其视为新的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
}

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

5 个答案:

答案 0 :(得分: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;
} 

这样,即使您没有对这些对象的引用,您仍会收到大量“测试”警报。

因此,我的猜测是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.

答案 1 :(得分:6)

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

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

答案 2 :(得分:2)

AFAIK,分配null应该清理它:images[i] = null

答案 3 :(得分:2)

摆脱铬和IE浏览器和EDGE的“naivists”所描述的错误。 您可以将图像源更改为空,以便占用零内存。

image.src = '';
image = null;

答案 4 :(得分:1)

我认为只有这样才能做到这一点:

for( i = 0; i < images.length; i++ ) 
  images[i] = null;
}

// or just 
images = null;