简体   繁体   中英

IE version Without conditional comments in javascript

I know how to test an ie version using the conditional comments . But, I found out a good and clean way to do it, by testing a javascript method and check if it's supported or not, like:

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

But, I don't know how to test it if it's an specific version (like, I want to do something if it's IE8 , but not if it's IE7 or IE9 nor other version.

I could use James Panolsey's solution

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;

}());

But it does test using Conditional Comments.


Why not Conditional Comments? Because of the Standards mode . As Microsoft states in their website and in the dev center , they do NOT support it in their new versions:

Important As of Internet Explorer 10, conditional comments are no longer supported by standards mode. Use feature detection to provide effective fallback strategies for website features that aren't supported by the browser. For more info about standards mode, see Defining Document Compatibility.


Testing by a valid Method is more efficient in my POV, But I don't know how to do it in a way to specific the version ... ("Using this you can test for that version"). The only one that I know is the above one that I used as example. Is there others methods that I could use to test it? or not?

While feature detection can be very useful, and is sometimes the quickest way to distinguish between supportive and non-supportive browser versions, detecting IE and its versions is actually a piece of cake:

var uA = navigator.userAgent;
var browser = null;
var ieVersion = null;
var htmlTag = document.documentElement;

if (uA.indexOf('MSIE 6') >= 0) {
    browser = 'IE';
    ieVersion = 6;
}
if (uA.indexOf('MSIE 7') >= 0) {
    browser = 'IE';
    ieVersion = 7;
}
if (document.documentMode) { // as of IE8; strictly IE proprietary 
    browser = 'IE';
    ieVersion = document.documentMode;
}

// Using it can be done like this: 
if (browser == 'IE' && ieVersion == 11)
    htmlTag.className += ' ie11';

.
That's all you need. You're catching higher IEs in lower Modes/Views as well with this script, including Compatibility ~.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM