Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. 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?

like image 242
P5music Avatar asked Mar 11 '12 09:03

P5music


2 Answers

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.

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);
like image 132
JKing Avatar answered Sep 18 '22 18:09

JKing


$('#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..

like image 3
Greg Avatar answered Sep 20 '22 18:09

Greg