<html> <head> <script language="javascript"> var arr = new Array(); function c() { var div = document.createElement("DIV"); document.body.appendChild(div); div.innerHTML = '<input type="button" value="从内部删除" onclick="f()"/><div style="position:absolute;top:110;left:110;width:1000px;height:1000px;-moz-opacity:0.07;filter:alpha(opacity=7);background-color:#000000"></div>'; arr.push(div); abcd.innerText = arr.length; } function f() { var tmp = arr.pop(); while(tmp!=null) { // for(var i = tmp.childNodes.count-1; i >=0 ; i--) // { // tmp.removeChild(tmp.childNodes[i]); // } document.body.removeChild(tmp); tmp = arr.pop(); } abcd.innerText = arr.length; } function g() { CollectGarbage(); } </script> </head> <body> <input type="button" value="添加" onclick="c();" /> <input type="button" value="删除" onclick="f();" /> <input onclick="g()" type="button" value="释放内存" /> <div id="abcd"></div> 典型的 半透明层 内存泄露问题:<br /> 测试:(必须在IE下测试才能发现问题)<br /> 1、依次执行“添加”“删除”“释放内存”,如此反复多次,发现内存可以正常释放。<br /> 2、依次执行“添加”“从内部删除”“释放内存”,如此反复多次,发现内存泄露无限制增长。 </body> </html>
<html> <head> <script language="javascript"> var arr = new Array(); function c() { var div = document.createElement("DIV"); document.body.appendChild(div); div.innerHTML = '<input type="button" value="从内部删除" onclick="f()"/><div style="position:absolute;top:110;left:110;width:1000px;height:1000px;-moz-opacity:0.07;filter:alpha(opacity=7);background-color:#000000"></div>'; arr.push(div); abcd.innerText = arr.length; } function f() { var tmp = arr.pop(); while(tmp!=null) { document.body.removeChild(tmp); tmp.childNodes[1].style.filter = "";//发现style的filter是个特殊的东西 需要手动释放一下 tmp = arr.pop(); } abcd.innerText = arr.length; this.onclick = null; } function g() { CollectGarbage(); } </script> </head> <body> <input type="button" value="添加" onclick="c();" /> <input type="button" value="删除" onclick="f();" /> <input onclick="g()" type="button" value="释放内存" /> <div id="abcd"></div> 典型的 半透明层 内存泄露问题:<br /> 测试:(必须在IE下测试才能发现问题)<br /> 1、依次执行“添加”“删除”“释放内存”,如此反复多次,发现内存可以正常释放。<br /> 2、依次执行“添加”“从内部删除”“释放内存”,如此反复多次,发现内存泄露无限制增长。 </body> </html>
function f() { var tmp = arr.pop(); while(tmp!=null) { document.body.removeChild(tmp); tmp.onclick = null;//onclick事件也最好置空一下 tmp = arr.pop(); } abcd.innerText = arr.length; }
<script type="text/javascript"> var arr = []; function c() { document.body.innerHTML += '<div id="tdiv_'+ arr.length + '">' + '<div style="position:absolute;top:110;left:110;width:1000px;height:1000px;-moz-opacity:0.07;filter:alpha(opacity=7);background-color:#000000"></div>' + '</div>'; arr[arr.length] = "tdiv_" + arr.length; } function f() { while(tmp = arr.pop()) { tmp = document.getElementById(tmp); if (tmp.outerHTML) tmp.outerHTML = ""; else tmp.parentNode.removeChild(tmp); } } </script> <input type="button" value="添加" onclick="c();" /> <input type="button" value="删除" onclick="f();" />