Search code examples
javascriptinternet-explorer-8internet-explorer-7conditional-compilation

How to use conditional compile to sniff IE8


I want to sniff the current version of IE8 (and I'm so sorry, but no other way, I have to do that). I know that feature sniffing should be used instead of browser sniffing, but hey, my boss doesn't know that, right?

Now I used this conditional compiling code:

var ie8 = false/*@cc_on @_jscript_version == 8@*/

But seems that it also includes IE7. Any idea?


Solution

  • Without using conditional compiles, you could use conditional comments to set a class on the html element for each IE you want to test for, like:

    <!--[if lt IE 7 ]> <html lang="en" class="ie6"> <![endif]-->
    <!--[if IE 7 ]>    <html lang="en" class="ie7"> <![endif]-->
    <!--[if IE 8 ]>    <html lang="en" class="ie8"> <![endif]-->
    <!--[if IE 9 ]>    <html lang="en" class="ie9"> <![endif]-->
    <!--[if (gt IE 9)|!(IE)]><!--> <html lang="en"> <!--<![endif]-->
    

    (from http://initializr.com/)

    Then it would be a simple matter of testing for the class in JS:

    var ie8 = !!document.getElementsByTagName("html")[0].className.match(/ie8/);