使用带有 RequireJS 的条件注释来加载 IE7/8 仅 jQuery

Using conditional comments with RequireJS to load IE7/8 only jQuery

本文关键字:IE7 加载 jQuery 注释 RequireJS 条件      更新时间:2023-09-26

我在我的项目中使用Require JS,它正在加载jQuery和其他一些与整个站点和所有浏览器相关的JavaScript文件。

但是,我需要在Internet Explorer 7和8上使用一些条件jQuery,我尝试将其放在页面的头部,脚本似乎无法找到jQuery,我假设这是因为它在jQuery之前加载。

 <script data-main="/@ViewBag.ScriptsFolder/main" src="/scripts/require.js" type="text/javascript"></script>
    <!--[if (gte IE 6)&(lte IE 8)]>
        <script type="text/javascript" src="/Scripts/ie.js"></script>
    <![endif]-->

有什么办法可以纠正这一点吗?我也在尝试以这种方式加载 Selectivizr,但由于同样的问题而不起作用。

谢谢

您可以在 html 元素上使用特定于 IE 的条件类,然后检查它并将 IE 依赖项加载到现有 main 脚本中。因此,文档的顶部如下所示:

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

然后在main.js 中,您可以使用:

if ($('html.lt-ie9').size()) {
    require(['/Scripts/ie'], function(ieScript) {
        // ... do stuff
    });
}

你不能使用你所描述的方法,因为require.js会寻找一个data-main属性来指定"入口点"——任何后续对require的调用都应该在Javascript中完成。