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

前端 未结 14 1759
失恋的感觉
失恋的感觉 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: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

提交回复
热议问题