Javascript Memory Leaks: Detached DOM tree

后端 未结 2 1234
醉话见心
醉话见心 2020-12-23 11:27

I have noticed that the memory of the browser starts increasing whilst I am in a form (this is noticeable from the task manager). In IE 9, this goes easily over 500MB after

2条回答
  •  粉色の甜心
    2020-12-23 12:08

    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.

提交回复
热议问题