How not to load a script in IE?

二次信任 提交于 2019-11-28 11:07:45

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

<![if !IE]>
    <script type="text/javascript" src="somescript.js"></script>
<![endif]>
yzxben
<!--[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/

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/

Vikram

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>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!