Do you know what may cause memory leaks in JavaScript?

There is a nice article about JavaScript and memory leaks. It does not specific about on browser, it rather describes the whole problematic of memory leaks and JavaScript.

  • JavaScript and memory leaks
  • Introducing the closure
  • More leakage patterns
  • Conclusion

I think it is a better approach to be as browser unspecific as possible insted of optimizing for a few browsers, when developing a website for the public.


Here is a classic memory leak in IE:-

function body_onload()
{
    var elem = document.getElementById('someElementId');
    // do stuff with elem
    elem.onclick = function() {
        //Some code that doesn't need the elem variable
    }
 }

After this code has run there is circular reference because an element has a function assigned its onclick event which references a scope object which in turn holds a reference to element.

someElement->onclick->function-scope->elem->someElement

In IE DOM elements are COM based reference counting objects that the Javascript GC can't cleanup.

The addition of a final line in the above code would clean it up:-

var elem = null;

In general; circular references are the cause of many problems. I remember IE 6 (not sure if it applies to 7) leaking quite badly with XMLHTTP... setting onreadystatechange = null once it was finished with fixed it.