how do I run a script only for IE 8

2019-03-22 07:22发布

问题:

I have a js file and would like to run some code only if the browser is IE 8. Is there a way I can do this?

Right now I only have this but it's for all ie browsers:

if ($.browser.msie) {
    //do stuff for IE 8
} 

回答1:

See Browser detection in JavaScript? and http://modernizr.com

Here is the short(est?) answer:

if (navigator.userAgent.match(/MSIE 8/) !== null) {
  // do something in IE8
}


回答2:

Browser specific code is almost never a good idea. However, if you must do this, you can put your code inside conditional comments.

http://www.positioniseverything.net/articles/cc-plus.html

<!--[if IE 8]>
  <script type="text/javascript">
    // this is only executed for IE 8
  </script>
<![endif]-->


回答3:

Alright people, I solved it myself like this:

if ($.browser.msie && $.browser.version == 8) {
    //my stuff

} 


回答4:

Could you do a call in the header to redirect the page if it is less than IE9? I find myself doing this often for my clients that use a mixture of IE6-10.

In the document head I call,

<!--[if IE 7]>  <link rel="()" type="()" href="(Your link here.)"><![endif]--> 

The other option you could look into is a shim or polyfil. There are many on the internet that help bridge the gap between modern web design and older browsers. An example is Modernizr.



回答5:

You can do it with conditional comments (by https://stackoverflow.com/a/10965091/1878731):

<!--[if IE 8 ]>    <html class="ie8"> <![endif]-->

if ($('html').is('.ie8')) {
    ...
}

Or without messing with html (by http://en.wikipedia.org/wiki/Conditional_comment):

<script>
/*@cc_on

  @if (@_jscript_version == 5.8) { // IE8 detected
    // do something
  }
@*/
</script>


回答6:

You can do something like this:

if (navigator.userAgent.indexOf('MSIE 8.0') !== -1) {
  // this clause will only execute on IE8
}


回答7:

$.browser is deprecated so you can not use this object property in new jQuery version so to support this you have to use the jQuery migrate plugin.Here is the link. https://github.com/jquery/jquery-migrate/#readme



回答8:

You can use the document.documentMode to get the version of IE.

switch(document.documentMode)
    {
        case 8:
            //do something with IE8
            break;
        case 9:
            //do something with IE9
            break;
        case 10:
            //do something with IE10
            break;  
        case 11:
            //do something with IE11
            break;
        default:
            console.log('Other browsers...');
    }

For documentation refer here



回答9:

Try using like this

<script type="text/javascript">
    if(/MSIE \d|Trident.*rv:/.test(navigator.userAgent))
        document.write('<script src="somescript.js"><\/script>');
</script>