Remove HTML element (DOM Node) from memory

Viewed 7677

according to mdn documentation the method removeChild removes a node from the DOM but it still resides in memory. My problem is that I want to delete it from memory as well. I've tried with the delete operator but the object is still there...

myCanvas.parentElement.removeChild(myCanvas);  // myCanvas actually removed from DOM
delete myCanvas;  // false. does nothing
alert(myCanvas); // shows HTMLCanvasElement instead of undefined
4 Answers

The basic answer is that all variables referencing the canvas need to be set to undefined so that the garbage collector can do its job. But sometimes it's not so simple in practice.

Here are several tricky situations I came across when trying to completely remove dynamically-created HTML canvas elements to avoid memory leaks:

(1) Methods I had added to the canvas element held their own references to it (creating a cycle). I fixed this by deleting all custom properties when removing the canvas:

function deleteAllProperties(obj) {
    for (var key in obj) {
        if (obj.hasOwnProperty(key)) {
            delete obj[key];
        }
    }
}
deleteAllProperties(myCanvas);
myCanvas = undefined;

(2) Internal variables in other objects still referenced the canvas. Fixed by setting them all to undefined:

_myVar = myBuilder = myObserver = undefined;

(3) A variable referenced the canvas' context: var ctx = myCanvas.getContext('2d'); This held on to the canvas in some browsers (even after setting myCanvas = undefined). Fixed by clearing that variable too:

ctx = undefined;
Related