1.常规
var addEvent=function(elem,type,handler){
if(window.addEventListener){
return elem.addEventListener(type,handler,false);
}
if(window.attachEvent){
return elem.attachEvent('on'+type,handler)
}
}
缺点:每次调用都会执行条件判断,可避免
2.改进,只在加载时做判断
var addEvent=(function(){
if(window.addEventListener){
return function(elem,type,handler){
elem.addEventListener(type,handler,false);
}
}
if(window.attachEvent){
return function(elem,type,handler){
elem.attachEvent('on'+type,handler);
}
}
})();
缺点:虽避免了判断,但如果从未使用过addEvent函数,那么第一次浏览器嗅探成为多余
3.惰性载入,重写函数
var addEvent=function(elem,type,handler){
if(window.addEventListener){
addEvenr=function(elem,type,hander){
elem.addEventListenr(type,handler,false)
}
}
else if(window.attachEvent){
addEvent=function(elem,type,handler){
elem.attachEvent('on'+type,handler);
}
}
addEvent(elem,type,handler);
};