简体   繁体   English

Javascript能够从HTML页面卸载图像吗?

[英]is Javascript able to unload an image from an HTML page?

I would like to know if it is possible to unload an image from an HTML page and free its memory occupation with some Javascript instructions. 我想知道是否可以从HTML页面卸载图像并通过一些Javascript指令释放其内存占用。 Say an image is already displayed on the screen. 假设图像已经显示在屏幕上。 Say I need to unload it to save memory (reason is not relevant here). 假设我需要卸载它以节省内存(原因与此无关)。 Can I do it with Javascript? 我可以使用Javascript吗?

The comments on your question are correct, you can remove it from the DOM, but the browser will clear it from memory when it decides it's good and ready. 您对问题的评论是正确的,您可以将其从DOM中删除,但是当浏览器确定它是好的并准备好时,浏览器将从内存中清除它。

To clear it from the DOM, you would do something like this: 要从DOM中清除它,您可以执行以下操作:

var badImage = document.querySelector("img#idOfImage"); 
//or "img[href='nameofimagefile.jpeg']" 
//whatever you need to do to get the right element
//then, remove it:

badImage.parentElement.removeChild(badImage);
$('#myDiv').remove();

or 要么

function removeElement(divNum) {
    var d = document.getElementById('myDiv');
    var olddiv = document.getElementById(divNum);
    d.removeChild(olddiv);
}

Would remove it from the DOM however it won't free up any memory, or bandwidth or http requests...so performance wise it won't make much of a difference (not taking rendering into account). 将它从DOM中删除但是它不会释放任何内存,带宽或http请求......所以性能方面它不会产生很大的差异(不考虑渲染)。

However I believe if the image is removed from the DOM the memory it uses will eventually be managed and removed by the browser (garbage collection). 但是我相信如果图像从DOM中删除,它使用的内存最终将被浏览器管理和删除(垃圾收集)。

So in short no I don't think there is a specific way to remove it from memory because that is a browser-level concern.. 所以简而言之,我不认为有一种特定的方法可以将其从内存中删除,因为这是一个浏览器级别的问题。

You can free memory of an img element by assigning the src attribute to a 1x1 pixel before removing it. 您可以通过在删除之前将src属性指定为1x1像素来释放img元素的内存。

const imgElement = document.querySelector(selector);
imgElement.setAttribute('src', '/images/pixel.gif');
imgElement.parentElement.removeChild(imgElement);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM