Using conditional comments with RequireJS to load

2019-03-22 02:24发布

问题:

I'm using Require JS in my project which is loading jQuery and some other JavaScript files that are relevant for the entire site and all browsers.

However, I need to use some conditional jQuery on Internet Explorer 7 & 8, I've tried putting this in the head of the page and the script doesn't seem to be able to find jQuery, I'm presuming this is because it's getting loaded before 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]-->

Is there any way to rectify this? I'm also trying to load Selectivizr in this way which isn't working because of the same problem.

Thanks

回答1:

You could use a conditional IE-specific class on the html element, then checking for it and loading the IE dependencies inside your existing main script. So, the top of the document would look like:

<!--[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> 

And then inside main.js, you could use:

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

You can't use the method you've described because require.js looks for a single data-main attribute to specify the 'entry point' - any subsequent calls to require should be done in Javascript.