How to dispose of DOM elements in JavaScript to avoid memory leaks How to dispose of DOM elements in JavaScript to avoid memory leaks javascript javascript

How to dispose of DOM elements in JavaScript to avoid memory leaks


The tricky part is figuring out where a reference still exists to the offending nodes.

You're doing this the hard way — you're adding all the markup to the page, then removing the stuff you don't want. I'd do it this way instead:

var div = document.createElement('div');// (Don't append it to the document.)$(div).html(xhtml);var stuffToKeep = $(div).find("form:eq(1)> *").filter(  function() {    return $(this).attr('id') !== '';  });parentObj.append(stuffToKeep);// Then null out the original reference to the DIV to be safe.div = null;

This isn't guaranteed to stop the leak, but it's a good start.


function discardElement(element) {    var garbageBin = document.getElementById('IELeakGarbageBin');    if (!garbageBin) {        garbageBin = document.createElement('DIV');        garbageBin.id = 'IELeakGarbageBin';        garbageBin.style.display = 'none';        document.body.appendChild(garbageBin);    }    // move the element to the garbage bin     garbageBin.appendChild(element);    garbageBin.innerHTML = '';}

Source


remove() and its ilk only remove elements from the DOM. They still exist in memory somewhere.

This is a known problem with AJAX and Web 2.0. There's little you can do aside from designing your site to ensuring that you occasionally have a page refresh to wipe things away.