2012-06-14 41 views
7

在JavaScript中創建新的圖像元素時,Google Chrome的內存工具(開發人員工具>時間軸>內存)自然會將其視爲新的DOM元素。配置圖像對象

在我的情況下,我結束了1500多個DOM元素,我希望擺脫它們。我試圖保存所有對象的數組,並刪除所有的人都在一個循環中時,我已經準備好創建的所有對象,導致以下錯誤:

Uncaught TypeError: Cannot call method 'removeChild' of null

表示圖像的對象不出現在實際的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對象?

回答

9

設置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; 
} 

這樣你仍然會得到很多的「測試」警報,即使你沒有對這些對象的引用。

因此,我猜測它是在瀏覽器的錯誤,而不是在你的代碼。

更新:翻翻鉻源之類的證明,(我的意思是這個文件的行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. 
+0

謝謝!我知道你的答案是最後一次,但你實際上已經做了一些研究 –

+0

這已得到修復,因爲或這仍然是一個錯誤嗎? – Hackeron

6

如果您沒有將它們添加到DOM(如使用appendChild父級),那麼removeChild是無用的。 Image對象只在內存中。

及銷燬在存儲物品,你只需要刪除這些對象的引用(如設置引用變量設置爲null),和垃圾收集將做休息。如果你不能將它們全部清零,它們將不會被GC化。

+0

最佳答案imo – sidonaldson

+0

只是好奇,如果你null對象將技術上仍然從GC'd後刪除從'圖像'分配的內存? –

1

我認爲唯一的辦法就是要做到這一點:

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

// or just 
images = null; 
2

據我所知,分配null應該清理:images[i] = null

2

爲了擺脫描述的bug通過Chrome和IE specilly和EDGE的 「naivists」。 你可以改變圖像源爲空,以便它取零內存。

image.src = ''; 
image = null;