10

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
}

Image オブジェクトを削除/削除/設定解除/破棄する方法はありますか?

4

5 に答える 5

12

設定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.
于 2012-06-14T11:42:33.780 に答える
7

それらをDOMに追加していない場合(appendChild親に使用するなど)は役に立ちませんremoveChild。Image オブジェクトはメモリ内にのみ存在します。

また、メモリ内のアイテムを破棄するには、これらのオブジェクトへの参照を削除するだけで済み (参照変数を null に設定するなど)、後はガベージ コレクションが行います。それらをすべて null にできない場合、それらは GC されません。

于 2012-06-14T11:25:04.710 に答える
2

私の知る限り、割り当てnullはそれをクリーンアップするはずです:images[i] = null

于 2012-06-14T11:25:29.743 に答える
1

唯一の方法はこれを行うことだと思います:

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

// or just 
images = null;
于 2012-06-14T11:25:16.317 に答える