如果我使用RequireJs,所有js函数都需要.js文件?

时间:2013-05-18 08:06:14

标签: javascript requirejs

我想在我的项目中使用RequireJs,但我发现我无法编写以下代码

<html>
   <head>
   </head>
   <body>
       <input type="button"  />
       <script>
           // Use the jQuery
           $(function() {
              //some code
             }
           )
       </script>
       <input />
       <input />

       // I had added the jQuery in required shim and jQuery is working in RequireJs.
       <script data-main="scripts/main" src="/scripts/require.js"></script>
   </body>
</html>

页面加载时出现错误$ is undefined。 我查了很多文章,但我无法解决。我怎么处理这个?我不想将示例js函数移动到.js文件。

5 个答案:

答案 0 :(得分:1)

正如你在问题中写的那样:

  

如果我使用requirejs,那么所有js函数都需要在.js文件中?

根据RequireJS的定义:

  

RequireJS是一个JavaScript文件和模块加载器。   使用像RequireJS这样的模块化脚本加载器可以提高代码的速度和质量。

因此,在您的网页中插入内联<script>标记不是一个好主意

但是,在回答你的问题时,因为RequireJS加载了脚本asynchronously,所以你不知道jQuery什么时候加载,而你不能使用内联脚本作为旧学校,您需要使用 definerequire方法 George Reiththe answer 中写道。

答案 1 :(得分:0)

您还必须包含jQuery。在requirejs.org上有一个whole manual page专门用来帮助你。

也许你想要的是here。取自那里:

require(["helper/util"], function(util) {
    //This function is called when scripts/helper/util.js is loaded.
    //If util.js calls define(), then this function is not fired until
    //util's dependencies have loaded, and the util argument will hold
    //the module value for "helper/util".
});

答案 2 :(得分:0)

Require.js甚至没有实现$。为什么你甚至在$(..)中包装你的功能?

答案 3 :(得分:0)

尝试在requirejs脚本标记之后移动示例脚本标记。目前,您的示例函数在requirejs有机会加载jQuery之前执行。

答案 4 :(得分:0)

第一件事$首先在JavaScript中没有任何意义,但受到热门jQuery library的使用。 JavaScript !== jQuery

其次假设你已经通过require.js加载了jQuery,你需要在之后放置你的初始脚本标记 <script data-main="scripts/main" src="/scripts/require.js"></script>因为它在require.js之前被调用。

第三,require.js异步加载文件,因此您必须将代码包含在require()define()标记中,并附带一系列依赖项,以便它们只在加载后调用它们。

e.g。

<html>
   <head>
       <script data-main="scripts/main" src="/scripts/require.js"></script>
   </head>
   <body>
       <input type="button"  />
       <script>
          /* 
             RequireJS is asynchronous so you must wrap your code
             in "require(["jQuery"], ...)" so it only calls it once
             jQuery has been loaded. Each included script is available 
             to you as a parameter in the callback function.
          */
          require(["jQuery"], function($) {
              $(function() {
              });
          });
       </script>
       <input />
       <input />
   </body>
</html>

您的设置应如下所示:

requirejs.config({
    paths: {
        'jQuery': 'path/to/jquery'
    },
    shim: {
        'jQuery': {
            exports: '$'
        }
    }
});