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?
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- How to fix IE ClearType + jQuery opacity problem i
- void before promise syntax
- Keeping track of variable instances
bah to conditional comments! Conditional code all the way!!! (silly IE)
Seriously though, just throwing this out there in case it suits you better... they're the same thing, this can just be in a .js file instead of inline HTML
Note: it is entirely coincidental that the jscript_version check is "9" here. Setting it to 8, 7, etc will NOT check "is IE8", you'd need to lookup the jscript versions for those browsers.
/MSIE\s(\d+)/.exec(navigator.userAgent)
null
so in that case||0
will switch thatnull
to0
[1]
will get major version of IE orundefined
if it was not an IE browser+
will convert it into a number,undefined
will be converted toNaN
NaN
with a number will always returnfalse
You are all trying to overcomplicate such simple things. Just use a plain and simple JScript conditional comment. It is the fastest because it adds zero code to non-IE browsers for the detection, and it has compatibility dating back to versions of IE before HTML conditional comments were supported. In short,
Beware of minifiers: most (if not all) will mistake the special conditional comment for a regular comment, and remove it
Basically, then above code sets the value of IE_version to the version of IE you are using, or -1 f you are not using IE. A live demonstration:
If I were you I would use conditional compilation or feature detection.
Here's another alternative:
Does it need to be done in JavaScript?
If not then you can use the IE-specific conditional comment syntax:
Using conditional comments, you can create a script block that will only get executed in IE less than 9.
Of course, you could precede this block with a universal block that declares
var is_ie_lt9=false
, which this would override for IE less than 9. (In that case, you'd want to remove thevar
declaration, as it would be repetitive).EDIT: Here's a version that doesn't rely on in-line script blocks (can be run from an external file), but doesn't use user agent sniffing:
Via @cowboy: