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.

번호 제목 글쓴이 날짜 조회 수
246 [Gemini] ajax 와 fetch 의 차이 황제낙엽 2025.01.04 3419
245 [검토 완료] 디바이스 카메라로 촬영한 사진을 서버에 업로드하기 샘플 황제낙엽 2024.11.21 3987
244 브라우저에서 이미지를 편집(crop 등) 할 수 있는 오픈소스 Cropper.js 황제낙엽 2024.11.16 3842
243 [ChatGPT] json data 의 정렬 [1] 황제낙엽 2024.07.23 3352
242 DOMContentLoaded 이벤트와 window.onload 이벤트 황제낙엽 2024.07.15 3669
241 fetch() 사용 예제들 황제낙엽 2024.07.09 3380
240 [Copilot] Vanilla JavaScript에서 외부 스크립트 파일에 정의된 함수들을 로드 황제낙엽 2024.06.21 3758
239 [Copilot] ES6 모듈(module) 문법 황제낙엽 2024.06.21 3805
238 [Copilot] JSON 객체 내부 데이터를 순회하면서 조회하는 코드 황제낙엽 2024.06.02 3270
237 [Copilot] JavaScript로 서버에 특정 값을 POST 방식으로 전달하고 응답을 기다리지 않고 바로 종료 황제낙엽 2024.05.31 3615
236 json 데이터 내의 변수명에 prefix 로 type 표현하기 황제낙엽 2024.04.15 3361
235 fetch() 함수 사용 예제 file 황제낙엽 2023.11.23 3605
234 현재 document 의 host 와 port 를 얻는 방법 황제낙엽 2023.10.03 4209
233 (Bard) FileReader 로 여러개의 파일을 read 하는 법 file 황제낙엽 2023.08.23 3660
232 How to build a file upload service with vanilla JavaScript file 황제낙엽 2023.08.22 3715
231 (Bard) JavaScript로 JSON 배열을 작성하는 방법 황제낙엽 2023.08.21 3672
230 모바일 브라우저에서 file input element 를 이용하여 여러장의 이미지를 서버에 전송하려 할때 [1] 황제낙엽 2023.08.21 3703
229 navigator.mediaDevices 황제낙엽 2023.08.21 3798
228 Barcode Detection API 황제낙엽 2023.08.06 3854
227 정규식을 이용한 이메일 검증 스크립트 file 황제낙엽 2023.06.25 2894