RequireJS,jquery仍未定义

时间:2014-12-29 16:43:59

标签: javascript jquery html requirejs undefined

我知道这已经讨论过了,但经过一段时间的搜索,我无法弄清楚为什么我的小设置无法正确加载jQuery与requireJS。

我在' file://'中运行了一个小样本html页面。并尝试通过调用require来加载2个模块:

  • jquery的
  • 我写的自定义模块

如果我的自定义模块正确加载(我可以在require调用中使用它的别名,jquery总是未定义的)

我尝试在require.config中设置路径,以及shim(导出' $'或' jQuery')但它不起作用。

我可以让jquery正确加载的唯一方法是删除所有路径定义并在我的文件系统上命名jquery文件' jquery.js'

这是我的配置:

main.js:

require.config({
    baseUrl: 'scripts',
    paths: {
        jquery: 'jquery-2.1.3.min' //does not work
        //jquery: 'http://code.jquery.com/jquery-2.1.3.min.js' //does not work either
    }
});

console.log( "main.js is loaded" );  //this is correctly ouputed to the console

test.html:

<!DOCTYPE html>
<html>
  <head>
  </head>
  <body>
    <!--
       ... page content ...
    -->

    <!-- main.js is loaded from data-main -->
    <script data-main="scripts/main" src="scripts/require.js"></script>
    <script type='text/javascript'>
      require(
          ['jquery','custom'],
          function($, Custom){
            console.info('$:');
            console.info($); //outputs undefined

            console.info('Custom:');
            console.info(Custom); //outputs my custom object        

          });
    </script>  
  </body>
</html>

再一次,如果我删除了jquery的所有路径定义,并且只需命名我的jquery js文件&#39; jquery.js&#39;但这很草率。

有人能指出我正确的方向吗?

1 个答案:

答案 0 :(得分:3)

问题是您通过main加载了data-main中的RequireJS配置。 data-main属性仅告诉RequireJS加载其中列出的模块,但加载仍然是异步,因此{/ 1}}可能会在 RequireJS尝试加载后加载 jQuery的。发生这种情况时,RequireJS无法找到jQuery,main未定义。 (顺便提一下,我建议在您的RequireJS配置中将$设置为enforceDefine,这样您就会收到一条错误消息,告诉您模块何时未加载。这比使用未定义的符号更好。)

一种解决方案是将您的配置移到true之外。因此,您将其从main中删除,并将其添加到一个加载RequireJS前面的main元素:

script

或者,您可以嵌套<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> 次来强制require加注,以便在任何其他模块之前加载:

main