I have heard that browser sniffing is bad , i have seen the below method used to detect if a browser is IE or not:
var isIe = !!window.ActiveXObject,
is it a reliable way to detect ie ?
I have seen this method used in plugins like HERE
I have heard that browser sniffing is bad , i have seen the below method used to detect if a browser is IE or not:
var isIe = !!window.ActiveXObject,
is it a reliable way to detect ie ?
I have seen this method used in plugins like HERE
Except in very rare cases (usually dealing with implementation bugs for which feature detection is not practical), making programming decisions based on the brand or version of the browser is considered a poor practice that leads to code that breaks as browsers change.
Creating a variable like isIE
and then using that for programming decisions makes an assumption that all browsers for which isIE
would be true
or false
all have the same behavior and this is exactly where browser detection breaks down. It's just wrong.
For example, IE8 didn't support .addEventListener()
, but IE9 and beyond does. And then in IE11, .attachEvent()
was removed.
So, if awhile ago, you used browser detection and wrote code like this:
if (isIE) {
elem.attachEvent(...);
} else {
elem.addEventListener(...);
}
Then, when IE started supporting .addEventListener()
in IE9 your code would continue to use the old way. Then, when IE11 came out when .attachEvent()
was removed, your code would break entirely because you'd still be detecting IE and trying to use the old way. So, your code was brittle because it assumes that detecting a browser type means a specific behavior which is just simply not true. Instead, you should detect the behavior itself, not the type of browser.
So, using feature detection:
if (elem.addEventListener) {
elem.addEventListener(...);
} else {
elem.attachEvent(...);
}
Then, your code just merrily continues to work in IE8, IE9, IE10, IE11, etc... Your code doesn't have to be "fixed" as the browser changes.