sitelink1  
sitelink2  
sitelink3  
sitelink4 http://1 
extra_vars4 ko 
extra_vars5 http://www.javascriptkit.com/javatutors/closuresleak/index3.shtml 
extra_vars6 sitelink1 

All of the patterns shown below are described in detail in Justing's article. I'm going through them just for the sake of completeness:

[Exhibit 5 - Circular reference because of expando property]
·미리보기 | 소스복사·
  1. <html>   
  2. <head>   
  3. <script type="text/javascript">   
  4.     var myGlobalObject;   
  5.   
  6.     function SetupLeak(){   
  7.         //Here a reference created from the JS World    
  8.         //to the DOM world.   
  9.         myGlobalObject=document.getElementById("LeakedDiv");   
  10.   
  11.         //Here DOM refers back to JS World;    
  12.         //hence a circular reference.   
  13.         //The memory will leak if not handled properly.   
  14.         document.getElementById("LeakedDiv").expandoProperty=   
  15.                                                myGlobalObject;   
  16.     }   
  17. </script>   
  18. </head>   
  19. <body onload="SetupLeak()">   
  20. <div id="LeakedDiv"></div>   
  21. </body>   
  22. </html>  

Here the global variable myGlobalObject refers to the DOM element LeakDiv; at the same time LeakDiv refers to the global object through its expandoProperty. The situation looks like this:

The above pattern will leak due to the circular reference created between a DOM node and a JS element.

Since the JScript garbage collector is a mark and sweep GC, you may think that it would handle circular references. And in fact it does. However this circular reference is between the DOM and JS worlds. DOM and JS have separate garbage collectors. Therefore they cannot clean up memory in situations like the above.

Another way to create a circular reference is to encapsulate the DOM element as a property of a global object:

[Exhibit 6 - Circular reference using an Encapsulator pattern]
·미리보기 | 소스복사·
  1. <html>   
  2. <head>   
  3. <script type="text/javascript">   
  4. function Encapsulator(element){   
  5.     //Assign our memeber   
  6.     this.elementReference = element;   
  7.   
  8.     // Makea circular reference   
  9.     element.expandoProperty = this;   
  10. }   
  11.   
  12. function SetupLeak() {   
  13.     //This leaks   
  14.     new Encapsulator(document.getElementById("LeakedDiv"));   
  15. }   
  16. </script>   
  17. </head>   
  18. <body onload="SetupLeak()">   
  19. <div id="LeakedDiv"></div>   
  20. </body>   
  21. </html>  

Here is how it looks like:

However, the most common usage of closures over DOM nodes is event attachment. The following code will leak:

[Exhibit 7 - Adding an event listener as a closure function]
·미리보기 | 소스복사·
  1. <html>   
  2. <head>   
  3. <script type="text/javascript">   
  4. window.onload=function(){   
  5.     // obj will be gc'ed as soon as    
  6.     // it goes out of scope therefore no leak.   
  7.     var obj = document.getElementById("element");   
  8.        
  9.     // this creates a closure over "element"   
  10.     // and will leak if not handled properly.   
  11.     obj.onclick=function(evt){   
  12.         ... logic ...   
  13.     };   
  14. };   
  15. </script>   
  16. </head>   
  17. <body>   
  18. <div id="element"></div>   
  19. </body>   
  20. </html>  

Here is a diagram describing the closure which creates a circular reference between the DOM world and the JS world.

The above pattern will leak due to closure. Here the closure's global variable obj is referring to the DOM element. In the mean time, the DOM element holds a reference to the entire closure. This generates a circular reference between the DOM and the JS worlds. That is the cause of leakage.

When we remove closure we see that the leak has gone:

[Exhibit 8- Leak free event registration - No closures were harmed]
·미리보기 | 소스복사·
  1. <html>   
  2. <head>   
  3. <script type="text/javascript">   
  4. window.onload=function(){   
  5.     // obj will be gc'ed as soon as    
  6.     // it goes out of scope therefore no leak.   
  7.     var obj = document.getElementById("element");   
  8.     obj.onclick=element_click;   
  9. };   
  10.   
  11. //HTML DOM object "element" refers to this function   
  12. //externally   
  13. function element_click(evt){   
  14.     ... logic ...   
  15. }   
  16. </script>   
  17. </head>   
  18. <body>   
  19. <div id="element"></div>   
  20. </body>   
  21. </html>  

Here is the diagram for the above code piece:

This pattern will not leak because as soon as the function window.onload finishes execution, the JS object obj will be marked for garbage collection. So there won't be any reference to the DOM node on the JS side.

And the last but not the least leak pattern is the "cross-page leak":

[Exhibit 10 - Cross Page Leak]
·미리보기 | 소스복사·
  1. <html>   
  2. <head>   
  3. <script type="text/javascript">   
  4. function LeakMemory(){   
  5.     var hostElement = document.getElementById("hostElement");   
  6.     // Do it a lot, look at Task Manager for memory response   
  7.     for(i = 0; i < 5000; i++){   
  8.         var parentDiv =   
  9.         document.createElement("<div onClick='foo()'>");   
  10.   
  11.         var childDiv =   
  12.         document.createElement("<div onClick='foo()'>");   
  13.   
  14.         // This will leak a temporary object   
  15.         parentDiv.appendChild(childDiv);   
  16.         hostElement.appendChild(parentDiv);   
  17.         hostElement.removeChild(parentDiv);   
  18.         parentDiv.removeChild(childDiv);   
  19.         parentDiv = null;   
  20.         childDiv = null;   
  21.     }   
  22.     hostElement = null;   
  23. }   
  24. </script>   
  25. </head>   
  26. <body>   
  27. <input type="button"    
  28.        value="Memory Leaking Insert" onclick="LeakMemory()" />   
  29. <div id="hostElement"></div>   
  30. </body>   
  31. </html>  

Since we observe memory leakage even in Exhibit 1, it is not surprising that this pattern leaks. Here is what happens: When we append childDiv to parentDiv, a temporary scope from childDiv to parentDiv is created which will leak a temporary script object. Note that document.createElement("<div onClick='foo()'>"); is a non-standard method of event attachment.

Simply using the "best practices" is not enough (as Justing has mentioned in his article as well). One should also adhere to standards as much as possible. If not, he may not have a single clue about what went wrong with the code that was working perfectly a few hours ago (which had just crashed unexpectedly).

Anyway, let us re-order our insertion. The code below will not leak:

[Exhibit 11 - DOM insertion re-ordered - no leaks]
·미리보기 | 소스복사·
  1. <html>   
  2. <head>   
  3. <script type="text/javascript">   
  4. function LeakMemory(){   
  5.     var hostElement = document.getElementById("hostElement");   
  6.     // Do it a lot, look at Task Manager for memory response   
  7.     for(i = 0; i < 5000; i++){   
  8.         var parentDiv =   
  9.           document.createElement("<div onClick='foo()'>");   
  10.   
  11.         var childDiv =   
  12.           document.createElement("<div onClick='foo()'>");   
  13.   
  14.         hostElement.appendChild(parentDiv);   
  15.         parentDiv.appendChild(childDiv);   
  16.         parentDiv.removeChild(childDiv);   
  17.         hostElement.removeChild(parentDiv);   
  18.   
  19.         parentDiv = null;   
  20.         childDiv = null;   
  21.     }   
  22.     hostElement = null;   
  23. }   
  24. </script>   
  25. </head>   
  26. <body>   
  27. <input type="button"    
  28.        value="Memory Leaking Insert" onclick="LeakMemory()" />   
  29. <div id="hostElement"></div>   
  30. </body>   
  31. </html>  

We should keep in mind that, although it is the market leader, IE is not the only browser in the world. And writing IE-specific non-standard code is a bad practice of coding. The counter-argument is true as well. I mean, saying "Mozilla is the best browser so I write Mozilla-specific code; I don't care what the heck happens to the rest" is an equally bad attitude. You should enlarge your spectrum as much as possible. As a corollary, you should write standards-compatible code to the highest extent, whenever possible.

Writing, "backwards compatible" code is "out" nowadays. The "in" is writing "forward compatible" (also known as standards compatible) code which will run now and in the future, in current and in future browsers, here and on the moon.

번호 제목 글쓴이 날짜 조회 수
117 Defining classes and inheritance (클래스 정의와 상속) 황제낙엽 2011.03.24 392
116 User Agent 관련 Reference URL 황제낙엽 2011.02.22 41
115 각 브라우저 별 User Agent 정보 황제낙엽 2011.02.22 823
114 History of User Agent 황제낙엽 2011.02.22 38
113 Navigator 객체란? 황제낙엽 2011.02.22 53
112 Understanding User-Agent Strings 황제낙엽 2011.02.22 76
111 User Agent 정보 모음 file 황제낙엽 2011.02.22 7767
110 ActiveX 설치 여부를 검사하는 스크립트 황제낙엽 2011.02.13 4053
109 [JavaScript Tutorials] Error handling in JavaScript using try/catch/finally - The Error object and throwing your own errors (해석중) 황제낙엽 2009.04.10 82
» [JavaScript Tutorials] More leakage patterns (해석중) 황제낙엽 2009.04.10 142
107 [JavaScript Tutorials] Introducing the closure (해석중) 황제낙엽 2009.04.10 555
106 [JavaScript Tutorials] JavaScript and memory leaks (해석중) 황제낙엽 2009.04.08 102
105 [JavaScript Tutorials] Handling runtime errors in JavaScript using try/catch/finally (해석중) 황제낙엽 2009.04.08 2784
104 JavaScript Closures for Dummies 황제낙엽 2009.04.08 227
103 자바스크립트 예약어 황제낙엽 2010.11.03 35
102 YUI Logger(Yahoo) 를 동적으로 로드하는 북마크릿 황제낙엽 2010.10.03 25
101 Javascript 를 사용하여 Binary File 읽기 황제낙엽 2010.09.29 499
100 크로스 브라우저를 위한 브라우저 검사 코드 file 황제낙엽 2010.08.27 86
99 Dynatrace For Ajax Performance 황제낙엽 2010.08.18 45
98 javascirpt IME-Mode 설정하기 황제낙엽 2010.08.17 1112