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?
var ie = !-[1,]; // true if IE less than 9
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 ;)
if (+(/MSIE\s(\d+)/.exec(navigator.userAgent)||0)[1] < 9) {
// IE8 or less
}
/MSIE\s(\d+)/.exec(navigator.userAgent)
null
so in that case ||0
will switch that null
to 0
[1]
will get major version of IE or undefined
if it was not an IE browser+
will convert it into a number, undefined
will be converted to NaN
NaN
with a number will always return false