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

前端 未结 14 1629
失恋的感觉
失恋的感觉 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 ;)

    0 讨论(0)
  • 2020-11-28 21:48
    if (+(/MSIE\s(\d+)/.exec(navigator.userAgent)||0)[1] < 9) {
        // IE8 or less
    }
    
    • extract IE version with: /MSIE\s(\d+)/.exec(navigator.userAgent)
    • if it's non-IE browser this will return 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
    • leading + will convert it into a number, undefined will be converted to NaN
    • comparing NaN with a number will always return false
    0 讨论(0)
提交回复
热议问题