Search code examples
javascripthtmlinternet-explorermeta-tagsconditional-comments

How to use meta tag in a browser version condition (IE 10 and above)?


I'm using IE11. And I have to force the browser to act as IE 10 with a condition if the browser is IE11. Because of Microsoft removed support for Conditional Comments, I'm struggling to figure out a way. I tried this with JavaScript,

<script language="JavaScript">
         function setVersion() {
             if (getInternetExplorerVersion() === 11) {
                 debugger;
                 $('head').append('<meta http-equiv="X-UA-Compatible" content="IE=10" />');
             }
         }
         //Method to get the IE version
         function getInternetExplorerVersion() {
             var rv = -1;
             if (navigator.appName == 'Microsoft Internet Explorer') {
                 var ua = navigator.userAgent;
                 var re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
                 if (re.exec(ua) != null)
                     rv = parseFloat(RegExp.$1);
             }
             else if (navigator.appName == 'Netscape') {
                 var ua = navigator.userAgent;
                 var re = new RegExp("Trident/.*rv:([0-9]{1,}[\.0-9]{0,})");
                 if (re.exec(ua) != null)
                     rv = parseFloat(RegExp.$1);
             }
             return rv;
         }
    </script>

Now because of getVersion is being called after loading the page, this code isn't making any effect. Any other way to do this?


Solution

  • you can use commented conditional comment like this

    <!--[if gt IE 9]><!-->
        <meta http-equiv="X-UA-Compatible" content="IE=10" />
    <!--<![endif]-->
    

    in this way ie10 and above will have the tag, instead ie9 and under will not have it cause the condition is not met.

    example:

    <!--[if lte IE 8]>
        <script type="text/javascript" src="/app.ie8.js"></script>
    <![endif]-->
    <!--[if gte IE 9]><!-->
        <script type="text/javascript" src="/app.ie8.js" defer></script>
    <!--<![endif]-->
    

    will load on ie8 the js without the defer, while in ie9 and above (and all other browser) will load the script with defer ignoring the conditional because they count as commented

    There a link to the Wiki for an explanation.