如果不是IE8或以前而不是移动设备,需要条件语句才能加载脚本

时间:2011-12-14 10:31:44

标签: jquery internet-explorer conditional

我以传统格式链接到我页面的head部分的脚本,即

<script src="scripts/scriptname.js" type="text/javascript"></script>

我想阻止在IE8及更早版本以及iPhone / iPad和移动设备上加载此脚本。

我有这个声明阻止它在IE8中运行,但我不知道如何调整它以包含早期版本的IE,我也不确定移动设备:

<!--[if !IE 8]><!-->
    <script src="scripts/scriptname.js" type="text/javascript"></script>
<!--<![endif]-->

有人可以帮忙吗?

谢谢,

尼克

1 个答案:

答案 0 :(得分:5)

<!--[if lt IE 9]>
     <script src="scripts/scriptname.js" type="text/javascript"></script>
<![endif]-->

这将包括Internet Explorer 8及更低版本的块(<=小于)。

但是 - 如果你必须仅为移动设备调整脚本,我认为javascript解决方案是最好的。 通过浏览器和设备的导航器对象检查用户代理,如下所示:

if( (navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i)) || ... )

包括所有移动设备可能太多了。按屏幕大小切换是一个好方法:

if ( screen.width <= 699 ) {
     // your script
}

使用浏览器检测来查找MSIE而不是9.0:

if ( screen.width <= 699 || navigator.userAgent.match(/MSIE\s(?!9.0)/) ) {
     // your script
}