What would be your fastest, shortest (best) way to detect browser which is IE and version less than 9 in JavaScript, without using jQuery or any add-on libraries?
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- How to fix IE ClearType + jQuery opacity problem i
- void before promise syntax
- Keeping track of variable instances
This hack is supported in ie5,6,7,8. It is fixed in ie9+ (so it suits demands of this question). This hack works in all IE compatibility modes.
How it works: ie engine treat array with empty element (like this [,1]) as array with two elements, instead other browsers think that there is only one element. So when we convert this array to number with + operator we do something like that: (',1' in ie / '1' in others)*1 and we get NaN in ie and 1 in others. Than we transform it to boolean and reverse value with !. Simple. By the way we can use shorter version without ! sign, but value will be reversed.
This is the shortest hack by now. And I am the author ;)
Javascript
You can then do:
By James Panolsey from here: http://james.padolsey.com/javascript/detect-ie-in-js-using-conditional-comments
for what it's worth:
This successfully targets IE 9+ because the
addEventListener
method was supported very early on for every major browser but IE. (Chrome, Firefox, Opera, and Safari) MDN Reference. It is supported currently in IE9 and we can expect it to continue to be supported here on out.Below is an improvement over James Padolsey's solution:
1) It doesn't pollute memory (James' snippet creates 7 unremoved document fragments when detecting IE11, for example).
2) It's faster since it checks for a documentMode value before generating markup.
3) It's far more legible, especially to beginning JavaScript programmers.
Gist link: https://gist.github.com/julianshapiro/9098609
I liked Mike Lewis' answer but the code did not pass jslint and I could not understand the funky while loop. My use case is to put up a browser not supported message if less than or equal to IE8.
Here is a jslint free version based on Mike Lewis':
I've decided to go with object detection instead.
After reading this: http://www.quirksmode.org/js/support.html and this: http://diveintohtml5.ep.io/detect.html#canvas
I'd use something like