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

前端 未结 5 479
不思量自难忘°
不思量自难忘° 2020-12-23 11:50

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 tha

5条回答
  •  -上瘾入骨i
    2020-12-23 12:01

    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.

提交回复
热议问题