一个普通的浏览器嗅探技术,每次都要调用addEvent进行判断,执行if语句。
// 浏览器嗅探技术:指的就是检测浏览器是否支持
var addEvent = function(elem, type, handler) {
if (window.addEventListener) {
return elem.addEventListener(type, handler, false);
}
if (window.attachEvent) {
return elem.attachEvent('on' + type, handler);
}
};
//这个函数的缺点是每次都会执行if语句
另一个加载技术,通过立即执行函数,加载的时候立即执行addEvent(),并且根据浏览器的不同返回一个新的匿名函数
var addEvent = (function() {
if (window.addEventListener) {
return function(elem, type, handler) {
elem.addEventListener(type, handler, false) //webkit、os
}
}
if (window.attachEvent) {
return function(elem, type, handler) {
elem.attachEvent('on' + type, handler) //IE浏览器
};
}
})()
惰性加载函数,相当于重新封装一次addEvent,页面一加载就加载addEvent函数,这个跟前面的很像,只不过是在函数内部重写addEvent
<body>
<div id="div1">div1</div>
</body>
<script type="text/javascript">
var addEvent = function(elem, type, handler) {
if (window.addEventListener) {
addEvent = function(elem, type, handler) {
console.log('chrome addEvent');
elem.addEventListener(type, handler, false)
}
} else if (window.attachEvent) {
addEvent = function(elem, type, handler) {
console.log('ie addEvent');
elem.attachEvent('on' + type, handler)
}
}
addEvent(elem, type, handler)
}
var div = document.getElementById('div1');
addEvent(div, 'click', function() {
alert(1);
})
addEvent(div, 'click', function() {
alert(2)
})
</script>