如何仅在IE中加载脚本

时间:2015-05-01 13:42:14

标签: javascript internet-explorer conditional-statements

我需要在Internet Explorer浏览器中触发特定脚本!

我试过这个:

<!--[if IE]> 
<script></script>
<![endif]-->

不幸的是,这实际上会阻止加载脚本。

编辑:对于每个人都在问我为什么需要这个:当使用一些动画时,IE使滚动非常跳跃。为了解决这个问题,我需要实现一个向IE提供平滑滚动的脚本。我不想将它应用到其他浏览器,因为它们不需要它而且这个脚本虽然使滚动更平滑也使它有点不自然。

6 个答案:

答案 0 :(得分:57)

我很好奇为什么你特别需要针对IE浏览器,但如果真的是你需要做的话,下面的代码应该有效:

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

正则表达式的前半部分(MSIE \d)用于检测Internet Explorer 10及更低版本。后半部分用于检测IE11(Trident.*rv:)。

如果浏览器的用户代理字符串与该模式匹配,它会将somescript.js附加到页面。

答案 1 :(得分:3)

您可以修改此脚本以运行特定于IE的JavaScript:

var ua = window.navigator.userAgent;
var msie = ua.indexOf("MSIE ");

if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./)) // If Internet Explorer, return version number
  alert('IE ' + parseInt(ua.substring(msie + 5, ua.indexOf(".", msie))));
else alert('otherbrowser');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

答案 2 :(得分:3)

如果仍然有人在考虑运行IE特定的Javascript,则此代码仍可以在IE(11)和非IE浏览器(Chrome,Firefox,Edge)上进行测试

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

答案 3 :(得分:1)

功能检测是一种更好的方法 - 我建议调查Modernizr以便在设备/浏览器能够支持时逐步增强您的解决方案。

这种基于CSS的方法有时也会起作用,具体取决于您的需要。

将其放入<head>

<!--[if lt IE 7]> <html class="lt-ie9 lt-ie8 lt-ie7"> <![endif]-->
<!--[if IE 7]>    <html class="lt-ie9 lt-ie8"> <![endif]-->
<!--[if IE 8]>    <html class="lt-ie9"> <![endif]-->
<!--[if gt IE 8]><!--> <html class=""> <!--<![endif]-->

reference article - http://www.paulirish.com/2008/conditional-stylesheets-vs-css-hacks-answer-neither/

答案 4 :(得分:0)

您可以使用javascript来检测IE并动态插入脚本:

var ua = window.navigator.userAgent;
if (ua.indexOf("MSIE ") != -1|| !!navigator.userAgent.match(/Trident.*rv\:11\./)) {
    var head = document.getElementsByTagName('head')[0];
    var script = document.createElement('script');
    script.setAttribute('src', 'YOUR_JS_SCRIPT.js');
    script.setAttribute('type', 'text/javascript');
    script.setAttribute('async', 'false');
    head.appendChild(script);
}

如果你可以使用jQuery,你可以使用更短的代码:

if (ua.indexOf("MSIE ") != -1 || !!navigator.userAgent.match(/Trident.*rv\:11\./)) {
    $.getScript('YOUR_JS_SCRIPT.js');
}

此帖here

中找到的解决方案

答案 5 :(得分:0)

在所有浏览器中,

currentScriptsupported,除了 IE

<script>
    // self-invoked wrapper for scoping the `document` variable
    !function( d ) {
        if( !d.currentScript ){
            var s = d.createElement( 'script' );
            s.src = 'ie.js';
            d.head.appendChild( s );
        }
    }(document)
</script>

以上内容将有条件地仅针对IE浏览器添加脚本文件。