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

前端 未结 5 485
不思量自难忘°
不思量自难忘° 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条回答
  •  半阙折子戏
    2020-12-23 12:21

    Setting to null was the solution here at least. (Firefox 69)

    In a project I am loading loads of images in batches of 1 - 5 for comparison. Images averaging 8-9MB. Without setting img elements to null after removal the RAM buildup was significant and as far as exhausting available memory.

    So, changed from this:

    function clear (n) {
        while (n.lastChild) {
            n.removeChild(n.lastChild);
        return n;
    };
    

    to this:

    function clear (n) {
        let x;
        while (n.lastChild) {
            x = n.removeChild(n.lastChild);
            x = null;
        }
        return n;
    };
    

    Now there is no RAM buildup at all.

提交回复
热议问题