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

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?

109586 次浏览

Javascript

var ie = (function(){


var undef,
v = 3,
div = document.createElement('div'),
all = div.getElementsByTagName('i');


while (
div.innerHTML = '<!--[if gt IE ' + (++v) + ']><i></i><![endif]-->',
all[0]
);


return v > 4 ? v : undef;


}());

You can then do:

ie < 9

By James Panolsey from here: http://james.padolsey.com/javascript/detect-ie-in-js-using-conditional-comments

You could do it in a quick and dirty fashion with a regular expression and .match():

if (navigator.userAgent.match(/MSIE\s(?!9.0)/)) {
// ie less than version 9
}

Does it need to be done in JavaScript?

If not then you can use the IE-specific conditional comment syntax:

<!--[if lt IE 9]><h1>Using IE 8 or lower</h1><![endif]-->

Using conditional comments, you can create a script block that will only get executed in IE less than 9.

<!--[if lt IE 9 ]>
<script>
var is_ie_lt9 = true;
</script>
<![endif]-->

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 the var 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:

with(document.createElement("b")){id=4;while(innerHTML="<!--[if gt IE "+ ++id+"]>1<![endif]-->",innerHTML>0);var ie=id>5?+id:0}

bah to conditional comments! Conditional code all the way!!! (silly IE)

<script type="text/javascript">
/*@cc_on
var IE_LT_9 = (@_jscript_version < 9);
@*/
</script>

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.

I've decided to go with object detection instead.

After reading this: http://www.quirksmode.org/js/support.html and this: http://diveintohtml5.ep.io/detect.html#canvas

I'd use something like

if(!!document.createElement('canvas').getContext) alert('what is needed, supported');

If I were you I would use conditional compilation or feature detection.
Here's another alternative:

<!--[if lt IE 9]><!-->
<script>
var LTEIE8 = true;
</script>
<!--<![endif]-->

for what it's worth:

    if(  document.addEventListener  ){
alert("you got IE9 or greater");
}

This successfully targets IE 9+ because the addEventListener method was supported very early on for every major browser but IE. (Chrome, Firefox, Opera, and Safari) MDN Reference. It is supported currently in IE9 and we can expect it to continue to be supported here on out.

This link contains relevant information on detecting versions of Internet Explorer:

http://tanalin.com/en/articles/ie-version-js/

Example:

if (document.all && !document.addEventListener) {
alert('IE8 or older.');
}

I liked Mike Lewis' answer but the code did not pass jslint and I could not understand the funky while loop. My use case is to put up a browser not supported message if less than or equal to IE8.

Here is a jslint free version based on Mike Lewis':

/*jslint browser: true */
/*global jQuery */
(function () {
"use strict";
var browserNotSupported = (function () {
var div = document.createElement('DIV');
// http://msdn.microsoft.com/en-us/library/ms537512(v=vs.85).aspx
div.innerHTML = '<!--[if lte IE 8]><I></I><![endif]-->';
return div.getElementsByTagName('I').length > 0;
}());
if (browserNotSupported) {
jQuery("html").addClass("browserNotSupported").data("browserNotSupported", browserNotSupported);
}
}());

Below is an improvement over James Padolsey's solution:

1) It doesn't pollute memory (James' snippet creates 7 unremoved document fragments when detecting IE11, for example).
2) It's faster since it checks for a documentMode value before generating markup.
3) It's far more legible, especially to beginning JavaScript programmers.

Gist link: https://gist.github.com/julianshapiro/9098609

/*
- Behavior: For IE8+, we detect the documentMode value provided by Microsoft.
- Behavior: For <IE8, we inject conditional comments until we detect a match.
- Results: In IE, the version is returned. In other browsers, false is returned.
- Tip: To check for a range of IE versions, use if (!IE || IE < MAX_VERSION)...
*/


var IE = (function() {
if (document.documentMode) {
return document.documentMode;
} else {
for (var i = 7; i > 0; i--) {
var div = document.createElement("div");


div.innerHTML = "<!--[if IE " + i + "]><span></span><![endif]-->";


if (div.getElementsByTagName("span").length) {
return i;
}
}
}


return undefined;
})();
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
}
  • 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

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,

var IE_version=(-1/*@cc_on,@_jscript_version@*/);

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:

var IE_version=(-1/*@cc_on,@_jscript_version@*/);
if (IE_version!==-1){
document.write("<h1>You are using Internet Explorer " + IE_version + "</h1>");
} else {
document.write("<h1>You are not using a version of Internet Explorer less than 11</h1>");
}