Javascript 是否存在清除从文档中删除的DOM子树的方法(至少停止加载此子树中的图像)?
我发现Javascript 是否存在清除从文档中删除的DOM子树的方法(至少停止加载此子树中的图像)?,javascript,jquery,cross-browser,Javascript,Jquery,Cross Browser,我发现document.removeChild()实际上并没有破坏DOM子树,而是将其与文档解除链接 对我来说,这意味着未链接子树中的图像在移除子树后的一段时间内继续加载和消耗内存 当然,我可以将图像的“src属性设置为空字符串或null,希望这能阻止它们被加载,从而节省流量。对不起,我还没有在很多浏览器上测试这个解决方案 但是,我想知道是否有更简单的方法(强制子树清除?) 以下是测试代码: var url = 'http://habrahabr.ru/images/bg-multilogo.p
document.removeChild()
实际上并没有破坏DOM子树,而是将其与文档解除链接
对我来说,这意味着未链接子树中的图像在移除子树后的一段时间内继续加载和消耗内存
当然,我可以将图像的“src
属性设置为空字符串或null
,希望这能阻止它们被加载,从而节省流量。对不起,我还没有在很多浏览器上测试这个解决方案
但是,我想知道是否有更简单的方法(强制子树清除?)
以下是测试代码:
var url = 'http://habrahabr.ru/images/bg-multilogo.png?nocache=' + Date.now(),
cleanTheSrc = !true, /* todo: change and play */
jQueryRemove = !true, /* todo: change and play */
cleanTheLink = !true; /* todo: change and play */
var img = document.createElement('img');
console.log('img created');
img.onload = function(){console.log('img loaded');};
img.onerror = function(){console.log('img aborted');};
img.src = url;
document.body.appendChild(img);
console.log('img added to DOM (synchronously)');
if (jQueryRemove) {
$(img).remove();
console.log('img removed from DOM using jQuery (synchronously)');
} else {
document.body.removeChild(img);
console.log('img removed from DOM natively (synchronously)');
}
if (cleanTheSrc) {
img.src = '';
}
if (cleanTheLink) { // GC does not help actually, leave these lines here for fun
img = null;
}
这向我们表明,从DOM中移除图像(或移除其父节点)后,图像将继续处于“隐藏”状态
我的问题是:
更新: 出于好奇:我们可以异步地从DOM中添加和删除元素,使用其他JS库并使用缓存,对我来说,这并没有带来任何解决方案
我添加了几行来尝试
jQuery.remove()
。就个人而言,我在jQuery 1.6+中得到了相同的结果。从DOM中添加和删除元素或其容器对图像加载没有影响。所以,这看起来是错误的方式。为了证明这一点,让我们在没有DOM操作行的情况下运行上面的示例
var url = 'http://habrahabr.ru/images/bg-multilogo.png?nocache=' + Date.now(),
img = document.createElement('img');
console.log('img created');
img.onload = function(){console.log('img loaded');};
img.src = url; // loads the image, no matter it's detached from DOM
解决方案 差不多
container.remove().find('img').attr('src', '');
它足够快速和简单 当您标记jquery时,我假设您已经在页面中加载了jquery。在这种情况下,只需使用function@giorgio:我尝试在jQuery中重写这个示例,得到了相同的结果
jQuery.remove()
似乎与nativeremoveChild()做了同样的事情。最后,我决定放置本机代码,不讨论jQuery的内部结构和实现。如果remove()
在您的情况下有效,请发布代码。实际上这是不可能的,那么窗口。停止但这并不理想。删除src属性没有任何效果,正如一些人错误地认为的那样。