内存泄漏
一、内存泄漏的种类和解决办法
a、循环引用
1 <html>
2 <head>
3 <script>
4 var myGlobalObject;
5 function SetupLeak()
6 { // First set up the script scope to element reference
7 myGlobalObject =document.getElementById("LeakedDiv");
8 // Next set up the element to script scope reference
9 document.getElementById("LeakedDiv").expandoProperty =myGlobalObject;
10 }
11 function BreakLeak()
12 {
13 document.getElementById("LeakedDiv").expandoProperty =null; //去除引用以便能够回收myGlobleObject的内存
14 }
15 </script>
16 </head>
17 <body onload="SetupLeak()" onunload="BreakLeak()">
18 <div id="LeakedDiv"></div>
19 </body>
20 </html>
还有一种情况,是在用对象封装DOM结点的时候,可能会造成循环引用:
1 <html>
2 <head>
3 <script language="JScript">
4 function Encapsulator(element)
5 {
6 // Set up our element
7 this.elementReference = element;
8
9 // Make our circular reference
10 element.expandoProperty = this;
11 }
12
13 function SetupLeak()
14 {
15 // The leak happens all at once
16 new Encapsulator(document.getElementById("LeakedDiv"));
17 }
18
19 function BreakLeak()
20 {
21 document.getElementById("LeakedDiv").expandoProperty =null;
22 }
23 </script>
24 </head>
25
26 <body onload="SetupLeak()" onunload="BreakLeak()">
27 <div id="LeakedDiv"></div>
28 </body>
29 </html>
解决办法:不持有node,释放;不传递,通过id方法获得,参数用id代替
jquery的解决方法:data方法,为对象绑定数据
jQuery.data( element, key, value )//绑定数据到键值上
jQuery.data(element,key)//获取绑定的值
b、闭包
1 <html>
2 <head>
3 <script language="JScript">
4 function AttachEvents(element)
5 {
6 // This structure causes element to ref ClickEventHandler
7 element.attachEvent("onclick", ClickEventHandler);
8 function ClickEventHandler()//闭包
9 {
10 // This closure refs element
11 }
12 }
13
14 function SetupLeak()
15 {
16 // The leak happens all at once
17 AttachEvents(document.getElementById("LeakedDiv"));
18 }
19
20 function BreakLeak()
21 {
22 }
23 </script>
24 </head\>
25
26 <body onload="SetupLeak()" onunload="BreakLeak()">
27 <div id="LeakedDiv"></div>
28 </body>
29 </html>
c、页面间泄漏
解决方法:改变插入顺序,采用mustache利用innerHTML渲染
d、伪泄漏
参考