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. 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?
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. 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?
Share Improve this question edited Apr 11, 2014 at 15:57 tshepang 12.5k25 gold badges97 silver badges139 bronze badges asked Mar 11, 2012 at 9:32 P5musicP5music 3,3372 gold badges39 silver badges93 bronze badges 3- 5 You can remove the image from DOM tree but its removal from memory is only up to your browser. – duri Commented Mar 11, 2012 at 9:34
- 1 As a follow up to @duri, browsers will garbage collect unused assets and free up memory eventually, although there is no API for that level of control from the user's perspective – jlb Commented Mar 11, 2012 at 9:43
- 2 you might want to make a testcase with a huge picture and watch the browser-memoryconsumption when removing it. Let me know, how browsers react;) – Christoph Commented Mar 11, 2012 at 10:07
3 Answers
Reset to default 9The ments 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.
To clear it from the DOM, you would do something like this:
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).
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).
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.
const imgElement = document.querySelector(selector);
imgElement.setAttribute('src', '/images/pixel.gif');
imgElement.parentElement.removeChild(imgElement);