Javascript Memory Leak..Help

XXX
2007-06-22
2013-04-26
  • XXX
    XXX
    2007-06-22

    Hi,

    I have 2 javascript functions as below:

    function cbload()

    {

    var obj2=null;

    var obj=null;

    var obj1=document;

    obj2=obj1.getElementById("parId");

    for (i=0;i<5;i++)

    {

    obj=obj1.createElement("div");

    obj.id="div_" + i.toString();

    obj2.appendChild(obj);

    obj=null;

    }

    obj=null;

    obj2=null;

    obj1=null;

    alert('done');

    }

    function cbunload()

    {

    var obj2=null;

    var obj=null;

    var obj1=document;

    obj2=obj1.getElementById("parId");

    obj=null;

    for (i=0;i<5;i++)

    {

    obj=obj1.getElementById("div_" + i.toString());

    obj2.removeChild(obj);

    obj=null;

    }

    obj=null;

    obj2=null;

    obj1=null;

    alert('done');

    }

    <input id="Submit1" type="button" value="Load" onclick="cbload()" />

    <input id="Button1" type="button" value="UnLoad" onclick="cbunload()" />

    when i see it using Drip-it tool, After a Load/Unload, I am still seeing DOM Leak as div_0 thru div_4.

    Can someone help me in how to completly remove this leak.

    Help will be much appreciated

         Report Abuse  

     
    • Johan @ Cordys
      Johan @ Cordys
      2007-06-25

      removeChild(..) will only remove the element from the DOM tree but the elements are not actually freed and the reference to the removed child(s) will exist until page closes. This is a 'pseudo leak'.

      Solution for this is:

      (see: http://outofhanwell.com/ieleak/index.php?title=Fixing_Leaks\)

      Pseudo-Leaks 

      To avoid pseudo-leaks, do not use removeChild to remove elements. Instead, set the parent's innerHTML to "" or use a function like this:

      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 = '';
      }