处理图像对象 [英] Dispose an image object

查看:115
本文介绍了处理图像对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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:

未捕获的TypeError:无法调用null的方法'removeChild'

这表明Image对象没有出现在实际的DOM中。

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
}

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

推荐答案

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

Setting images = null would remove your reference in code to the object. However, to implement its load event, Chrome has to have its own internal reference to the object.

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

That is, you could have code like this:

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

这样你仍会得到很多测试警报,即使你没有对这些对象的引用。

This way you would still get a lot of "Test" alerts, even though you do not have a reference to these objects.

因此,我的猜测是Chrome中的错误,而不是代码中的错误。

Hence, my guess is that it is a bug in Chrome, not in your code.

更新:通过Chromium来源查看证明(我的意思是对此文件的第67-71行的评论,尤其是FIXME注释 http://code.google.com /searchframe#OAMlx_jo-ck/src/third_party/WebKit/Source/WebCore/bindings/v8/custom/V8HTMLImageElementConstructor.cpp ):

Update: looking through the Chromium source sort of 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.


这篇关于处理图像对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆