Javascript Memory Leaks: Detached DOM tree

There are many considerations to keep in mind when you write code that references DOM elements. But it all basically boils down to a couple of simple points –

a. Within your local functions always clear the reference

var menu = $('body #menu');
// do something with menu
 .
 .
 .
 menu = null;

b. Never store references as part of element data .data()

c. Try not to use DOM references inside closures/inline handlers, instead pass identifiers

    function attachClick(){
      var someDiv = $('#someDiv');

      someDiv.click(function(){
         var a = someDiv....;
         //Wrong. Instead of doing this..
      });


      someDiv.click(function(){
         var a = $('#someDiv');
         //Pass the identifier/selector and then use it to find the element
      });       


      var myFunc = function(){
         var a = someDiv;
         //using a variable from outside scope here - big DON'T!             
      }
    }

Yes, one can argue that searching elements can slow the page down, but the delay is very minimal when compared to the performance hit a huge heap causes esp. in large single page applications. Hence, #3 should be used only after weighing the pros and cons. (It did help significantly in my case)

UPDATE

d. Avoid anonymous functions – Naming your event handlers and local functions will help you a lot while profiling/looking at heap snapshots.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)