RequireJS, jquery still undefined

前端 未结 1 968
长情又很酷
长情又很酷 2021-01-15 15:45

I know this has already been discussed, but after searching for a while I can\'t figure out why my small setup does not load jquery correctly with requireJS.

I\'m ru

相关标签:
1条回答
  • 2021-01-15 16:14

    The problem is that you load your RequireJS configuration, which is in main, through data-main. The data-main attribute merely tells RequireJS to load the module listed there but the loading is still asynchronous, so main may load after RequireJS tries to load jQuery. When this happens, RequireJS fails to find jQuery and $ is undefined. (Incidentally, I'd suggest setting enforceDefine to true in your RequireJS configuration so that you get an error message telling you when a module has not loaded. That's a better clue than having an undefined symbol.)

    One solution would be to move your configuration outside of main. So you remove it from main and add it to a script element in front of the one loading RequireJS:

    <script>
    // RequireJS will use the value of `require` as its configuration.
    require = {
        baseUrl: 'scripts',
        paths: {
            jquery: 'jquery-2.1.3.min'
        },
        enforceDefine: true
    };
    </script>
    <script src="scripts/require.js"></script>
    

    Or you can nest require calls to force main to load before any other module:

    require(['main'], function () {
        require(['jquery','custom'], ...
    });
    
    0 讨论(0)
提交回复
热议问题