Best way to check for IE less than 9 in JavaScript without library

前端 未结 14 1756
失恋的感觉
失恋的感觉 2020-11-28 21:10

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?

14条回答
  •  囚心锁ツ
    2020-11-28 21:46

    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 ;)

提交回复
热议问题