Conditional comments alternative to load jQuery

2019-08-18 02:31发布

问题:

Because jQuery 2+ doesn't support IE 8, I'll need to make use of a previous version: jQuery 1.9.

Is there a way to include jQuery 1.9 when using IE <= 8 and jQuery 2+ when using IE > 8. I tried it with Conditional comments:

<!--[if lt IE 9]><!--><script> .. googleapis jquery 1.9 .. </script><!--<![endif]-->
<!--[if gte IE 9]><!--><script> .. googleapis jquery 2+ .. </script><!--<![endif]-->

The problem is that It is not working and I found some information about it not being supported anymore: http://msdn.microsoft.com/en-us/library/ie/hh801214(v=vs.85).aspx

Is there another way?

回答1:

You want the IE8 version to be in a commented-out block, but the non-IE9 version not to be:

<!--[if lt IE 9]> <script> .. googleapis jquery 1.9 .. </script> <![endif]-->
<![if !IE|gte IE 9]> <script> .. googleapis jquery 2+ .. </script> <![endif]>

Live Example with alerts

IE8 recognizes conditional comments, but other browsers don't (including newer IEs).

You also probably want to have !IE in the second one, just for completeness, as above.



回答2:

This will serve a different version of jQuery to Internet Explorer versions 6-8:

<!--[if lt IE 9]>
    <script src="jquery-1.9.0.js"></script>
<![endif]-->
<!--[if gte IE 9]><!-->
    <script src="jquery-2.0.0.js"></script>
<!--<![endif]-->

or the somewhat easier to read (but functionally identical):

<!--[if lt IE 9]>  
    <script src="jquery-1.9.0.js"></script>  
<![endif]-->  
<!--[if (gte IE 9) | (!IE)]><!-->  
    <script src="jquery-2.0.0.js"></script>  
<!--<![endif]--> 


回答3:

Bravo to T.J. Crowder (above) for his answer. This one racked my brain, I was having some trouble as IE8 was loading both JQuery files at times or the script I wrote would not allow JQuery to fire afterward due to the way the document was loading. One addition to the above answer, I actually had to reverse the order of the two conditionals in order to ensure more than one copy of JQuery was not loading in IE8.

<![if !IE|gte IE 9]> <script src="http://code.jquery.com/jquery-2.1.1.min.js"></script> <![endif]> <!--[if lt IE 9]> <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script> <![endif]-->



回答4:

You could check the UserAgentString on server code, and include one or another depending on it. Here is a list of Internet Explorer User Agents:http://www.useragentstring.com/pages/Internet%20Explorer/