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

109,396

Solution 1

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

Solution 2

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.

Solution 3

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}

Solution 4

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.

Solution 5

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;
})();
Share:
109,396

Related videos on Youtube

bcm
Author by

bcm

Updated on July 05, 2022

Comments

  • bcm
    bcm almost 2 years

    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?

    • Dan
      Dan over 12 years
      Don't forget that feature detection is the most reliable thing when you want to use a version-specific feature (However, the feature can exist but be buggy in some version, keep this in mind). If you want to display browser version on the page, use browser detection.
    • bcm
      bcm about 10 years
      I agree Dan, but in truth, it's often not straight-forward and/or easy for everyone to tie a particular difference to a feature (detection). Even if it is, the code may be easier to read when it is like the answer provided (example: ie < 9).
  • bcm
    bcm about 13 years
    JavaScript solution, not in the DOM
  • bcm
    bcm about 13 years
    creating a global variable using conditional tags... interesting.
  • Yahel
    Yahel about 13 years
    It has the advantage of not involving any RegEx and, presumably, not being spoofable. IE parses the variable like its nothing. (Which, for IE, is saying something.)
  • bcm
    bcm about 13 years
    this is pretty good, I could use if(window.ielt9). I wonder if there could there be a non-inline script solution that is better than this? (which would be posh...)
  • Yahel
    Yahel about 13 years
    It seems like @cwolves's solution would allow you to run it in an external script (I've never tried it.)
  • bcm
    bcm about 13 years
    @cwolves how is this differentiating between IE less than 9 and IE9? seems to be returning the same result?
  • None
    None about 13 years
    @bcm - you should get IE_LT_9 == false in IE9 and true in IE8. I'm using a mac right now and don't have a PC here, so I can't test it, but I pulled that out of code I wrote that I know works. If it's not working for some reason, alert(@_jscript_version) to see what you get and adjust from there.
  • bcm
    bcm about 13 years
    @cwolves it is returning 9 regardless of IE browser version on PC. so it's a no-go.
  • None
    None about 13 years
    sigh the code works, IE9 doesn't actually run IE7 when it's in 'compatibility mode', it still uses IE9's JS engine. jsfiddle.net/aNGXS According to IETester: IE9 says `9', IE8 says '5.6'
  • bcm
    bcm about 13 years
    I wouldn't depend on IETester, I just tried and it didn't even give me a result for IE8 on my pc. IE dev tool might be more reliable, or even better, standalone.
  • None
    None about 13 years
    either way, use a stand-alone version of IE8 and you WILL NOT get '9' in that alert. You'll get '5.8' or something similar (not sure specifically if they ever updated the JScript engine, but it's NOT 9)
  • None
    None about 13 years
    OMFG, I just tested this on FIVE machines via RDC and it works on EVERY one. IE8 says '5.8', IE9 says '9'. You're doing something wrong or assuming that you're not using the IE9 engine when you are. As I said, IE9 in "compatibility mode" or with a different user agent is still IE9. Run a stand-alone version of IE8, IE7 or anything previous and the code works.
  • bcm
    bcm about 13 years
    I'm just switching between BrowserMode+DocumentMode in IE dev toolbar, matching 7-7, 8-8 and 9-9. nothing unusual.
  • None
    None about 13 years
    You're still running IE9 though! This detects -THAT-. If you run a standalone copy if IE8, it'll show that. Don't blame me for Microsoft dev tools being worthless.
  • bcm
    bcm about 13 years
    just wondering... is all these (div, all) just in memory or is the DOM actually being accessed multiple times to get the version?
  • Mike Lewis
    Mike Lewis about 13 years
    It is just in memory, the div it creates doesn't actually get added to the DOM.
  • Tim Büthe
    Tim Büthe over 10 years
    Hmm, is this regular while syntax? Or some sort of a hack?
  • Brad Christie
    Brad Christie over 10 years
    @TimBüthe: The comma operator. Essentially it's adding the inner HTML and returning all[0] (which is the first <i> in the div). As long as the result is "truthy" (an <i> was found), it goes up an IE version and continues on.
  • Admin
    Admin over 10 years
    because jquery 2.x doesn't support ie < 9 so that piece of code would result in errors and crash and fear and doom.
  • Rup
    Rup almost 9 years
    Can you explain how / why that works? It looks like a bit of a nasty hack: you're relying on JavaScript engine quirks and that particular versions of the JavaScript engine correspond to particular IE versions. Does that still work in newer IEs set to back compatibility in the debug tools, or compatibility mode?
  • Aleko
    Aleko almost 9 years
    This hack is supported in ie5,6,7,8. It is fixed in ie9+ (so it suits demands of this question). 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.
  • Rup
    Rup almost 9 years
    OK, but if I put IE 9 into IE 7 compatibility mode will it detect IE 7? Thanks for the explanation, though - that would be better edited into the answer rather than left as a comment.
  • user2662680
    user2662680 over 8 years
    I like your answer best. Simple, not many lines of code and flexible.
  • daviestar
    daviestar about 8 years
    It's worth noting IE no longer supports conditional comments IE10+