当在 javascript 中创建一个新的图像元素时,谷歌浏览器的内存工具(开发者工具 > 时间轴 > 内存)自然地将其视为一个新的 DOM 元素。
在我的例子中,我最终得到了 1500 多个 DOM 元素,我希望摆脱它们。我试图将所有对象保存在一个数组中,并在我准备好创建所有对象时循环删除所有对象,导致以下错误:
未捕获的类型错误:无法调用 null 的方法“removeChild”
这表明 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
}
有没有办法移除/删除/取消设置/处置图像对象?
最佳答案
设置 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.
关于javascript - 处置图像对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11032018/