I originally posted this as a gist, here. I thought it best to keep my readers informed so that’s why I’m posting it here too:
// ---------------------------------------------------------- // A short snippet for detecting versions of IE in JavaScript // without resorting to user-agent sniffing // ---------------------------------------------------------- // If you're not in IE (or IE version is less than 5) then: // ie === undefined // If you're in IE (>=5) then you can determine which version: // ie === 7; // IE7 // Thus, to detect IE: // if (ie) {} // And to detect the version: // ie === 6 // IE6 // ie > 7 // IE8, IE9 ... // ie < 9 // Anything less than IE9 // ---------------------------------------------------------- // UPDATE: Now using Live NodeList idea from @jdalton var ie = (function(){ var undef, v = 3, div = document.createElement('div'), all = div.getElementsByTagName('i'); while ( div.innerHTML = '<!--[if gt IE ' + (++v) + ']><i></i><![endif]-->', all[0] ); return v > 4 ? v : undef; }()); |
Thanks for reading! Please share your thoughts with me on Twitter. Have a great day!
Ooh, that’s really clever! Thanks James!
that is cool , using what ie cant do in order to see if it is ie, that is crazy good.
I just got some ideas of how to use this in a webapp.
Thanks dude
Nice tips! That’s really clever! Thanks James! Keep on the good job!
W000000000W :). Realy nice.
Thanks its always good to be able to see who is still using the very bad ie browser.
There’s a much easier way to do that.
Usage:
if (IE) {...}
,if (IE <= 6) {...}
,if (IE < 9) {...}
,if (IE == 7) {...}
etc.//@cc_on
is a conditional comment, just like<!--[if IE]>
. Since it’s a comment, other browsers will just ingore it.Sure it’s cleaver, but how is this any different from testing navigator.appName and all the other navigator.* properties ?
You’ve still got to put IE specific code in regardless.
James’ solution is 191 bytes minified, but mine is only 40.
@Nyuszika7H: I think you meant
So is not 40 bytes anymore 😛
Anyway, a more accurate IE detection:
This way you when IE_Version != IE_Engine the user is either using compatibility mode or cloaking
@Nyuszika7H, @Aldo, you’re both missing the point. My solution doesn’t rely on feature detection/inference or sniffing the UA string. Both these things are considered bad-practice by some and so I wanted to offer a potential solution. There are smaller solutions available if you are not concerned about the arguments against.
Hey James, That was useful clear, and helpful info as usual from Webapp. Thanks and keep on the good works. ..
I like the code … It’s clean and short … Great work James
Like it a lot, nice and clean. Thanks for posting this. Nice to see new ways of detecting the bane of our lives!