日期:2014-05-16  浏览次数:20399 次

如何减少javascript事件对内存性能的影响
我们知道浏览器使用的是os的内存,而且是受限制的,远小于os内存,
如果在页面里添加了过多的事件,那么由于事件处理函数过多,会造成内存占用过大,严重影响性能,同时过多的事件会降低页面的交互性。
那么如何有效减少事件处理函数的个数呢?

< ul id=”myLinks” >
< li id=”goSomewhere” > Go somewhere < /li >
< li id=”doSomething” > Do something < /li >
< li id=”sayHi” > Say hi < /li >
< /ul >

//优化前
var item1 = document.getElementById(“goSomewhere”);
var item2 = document.getElementById(“doSomething”);
var item3 = document.getElementById(“sayHi”);
EventUtil.addHandler(item1, “click”, function(event){
location.href = “http://www.wrox.com”;
});
EventUtil.addHandler(item2, “click”, function(event){
document.title = “I changed the document ’ s title”;
});
EventUtil.addHandler(item3, “click”, function(event){
alert(“hi”);
});


//优化后
var list = document.getElementById(“myLinks”);
EventUtil.addHandler(list, “click”, function(event){
event = EventUtil.getEvent(event);
var target = EventUtil.getTarget(event);
switch(target.id){
case “doSomething”:
document.title = “I changed the document ’ s title”;
break;
case “goSomewhere”:
location.href = “http://www.wrox.com”;
break;
case “sayHi”:
alert(“hi”);
break;
}
});


2.及时移除事件,释放内存
先看一个反例:
< div id=”myDiv” >
< input type=”button” value=”Click Me” id=”myBtn” >
< /div >
< script type=”text/javascript” >
var btn = document.getElementById(“myBtn”);
btn.onclick = function(){
//do something
document.getElementById(“myDiv”).innerHTML = “Processing...”; //Bad!!!
};
< /script >


正解:
< div id=”myDiv” >
< input type=”button” value=”Click Me” id=”myBtn” >
< /div >
< script type=”text/javascript” >
var btn = document.getElementById(“myBtn”);
btn.onclick = function(){
//do something
btn.onclick = null; //remove event handler
document.getElementById(“myDiv”).innerHTML = “Processing...”;
};
< /script >