Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
615 views
in Technique[技术] by (71.8m points)

javascript - How can I prevent memory leaks when removing images in the DOM?

There is a known bug in webkit that when you remove an image from the DOM, it doesn't free the memory associated with it.

This is an issue with single page apps that often load images.

Various suggested solutions are:

The first 3 methods don't work for me. The main drawback to recycling image elements is that it means writing lots of code to manage that. I'm loading new HTML via AJAX that may contain images, so I don't necessarily know the number of images that will be loaded.

Are there any other work arounds to fix this problem?

question from:https://stackoverflow.com/questions/13859041/how-can-i-prevent-memory-leaks-when-removing-images-in-the-dom

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I have used 3 different types of approaches...

First. Did add a set of images and left the garbage collection to browser. enter image description here

It definitely garbage collected, but after a while, making sure that there exists no need for the images which have been created.

Second. Used a data:URI patterns for the src for images.

var s = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==";

for (var i = 0; i < 100; i++){
    var img = document.createElement("img");
    img.src = s;
document.getElementById("myList1").appendChild(img);
setTimeout(function(){img = null;}, 1000);
}

enter image description here

This looked similar, though a bit better for me as I was watching in front of my browser and observed a lesser memory was used, and garbage collection was almost the same as above.

Third. Did garbage collection in code.

var s = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==";

for (var i = 0; i < 100; i++){
    var img = document.createElement("img");
    img.src = "dot.png";  // or the other, both mean the same here.
    img.src = s;
document.getElementById("myList1").appendChild(img);
setTimeout(function(){img = null;}, 1000);
}

enter image description here

In this short time of testing, I believed that the last approach worked better, as it was almost freeing the space up immediately without waiting to see if there was any need for the referenced images further.

All in all, You better use garbage collection by yourself, when you absolutely feel like something must be freed off.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...