开发者

How not to load a script in IE?

It's possible to load a script only in IE with开发者_如何学JAVA conditional comments

<!--[if lte IE 7]>
    <script type="text/javascript" src="somescript.js"></script>
<![endif]-->

but what if I don't want to load it in IE lte 7 (but still need it in all other browsers)?

Any simple solutions?

P.S. I have a problem with SyntaxHighlighter - too many code slows IE7 down and since I'm short of time, I decided just to turn it off in IE7 for now.


This post says you can use the ! (NOT) operator like [if !IE]


<![if !IE]>
    <script type="text/javascript" src="somescript.js"></script>
<![endif]>


<!--[if gte IE 7]>
    <script type="text/javascript" src="somescript.js"></script>
<![endif]-->
<!--[if !IE]>
    <script type="text/javascript" src="somescript.js"></script>
<![endif]-->


This syntax works good (the script wouldn't be commented in firefox, chrome and so on):

<!--[if !IE]><!-->
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<!--<![endif]-->


You could try detecting the browser server-side and then echo the appropriate script includes.

The following has an example on simplistic browser detection in PHP:

http://www.php-scripts.com/20050912/12/


Since conditional statements are not Working in IE (10,11) and only IE(11) is supported by Microsoft and if anyone is still looking at running IE specific JavaScript then this code still works tested in IE(11), and non IE browsers(Chrome,Firefox,Edge).

<script type="text/javascript">
    if(/MSIE \d|Trident.*rv:/.test(navigator.userAgent)) 
        {document.write('<script src="../nolng/js/ex1IE.js"><\/script>');}
    else 
        {document.write('<script src="../nolng/js/ex1.js"><\/script>'); // for Chrome,Firefox,Edge}
</script>


I used the examples shown here and elsewhere, and it is really frustrating to see how many places this code example is messed up. Turns out the answer is simple, IE has special 'conditionals' like [if IE], but other browsers need comments to work with the 'conditionals'.

For example, since JQuery 2 doesn't work with IE8, you can do something like this

<!--[if IE ]>  (following is only visible to IE)
    <script src="./js/lib/jquery-1.6.1.min.js"></script>
<![endif]-->
<!--[if !IE]>-->  (extra comment - only visible to non-IE)
    <script src="./js/lib/jquery-2.1.1.min.js"></script>
    <script src="./js/lib/jquery.mobile-1.4.5.min.js"></script>
<!--<![endif]-->

I have verified the above works in Firefox, Chrome, IE8, Dolphin mobile, and Chrome mobile. You can also specify version. For example, less than IE 9 would be: <!--[if lt IE 9 ]>

For a detailed explanation, check out http://www.sitepoint.com/web-foundations/internet-explorer-conditional-comments/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜