1

I am experiencing some issue with requireJS, to which I am not familiar

I have this tree app/

public/
 master.html
 js/
   main.js
   app.js
   lib/ 
      jquery.js
      require.js
   vendor
       upload/
             vendor/
               dependency_upload.js //a bunch of dependencies file
             ulpload.js
       slider/
             dependency_slider.js //a bunch of dependencies file
             slider.js

in master.html file :

<script data-main="js/main" src="js/lib/require.js"></script>

In my main.js file

require(['js/lib/jquery.js']);

require({
    paths: {
        'dependency_upload': 'vendor/upload/vendor/dependencies'
    }
}, ['js/vendor/upload/upload.js'], function(App) {
    App.upload();
});


require(['js/app.js']);

require({
    paths: {
        'dependency_slider' : 'vendor/slider/dependencies'
    }
}, ['js/vendor/slider/slider.js'], function(App) {
    App.slider();
});

and each of upload.js or slider.js have the following structure. Here $myfunction stands here respectively for upload and slider

define(['dependency_$myfunction'],function() {
        function $myfunction(){ 
            ...
        }
        return{
            $myfunction: $myfunction
        }
    }
);

I have two problems,

1) The behaviour of the js loading is unstable : once two, jquery is not recognized. Btw, upload.js and slider.js share dependencies and some function of slider.js that are set inside these shared dependencies are said to be undefined (perhaps some files are loaded twice ?). So, am I correct with my requireJS usage ?

4

1 回答 1

1

模块加载是异步的,所以如果你真的需要在另一个模块之前加载 jQuery,你必须做以下两件事之一:

1 - 使用 jquery 要求中的回调函数,以便在加载 jquery 之前不要尝试加载另一个:

require(['js/lib/jquery.js'], function($) {    
    require({
        paths: {
            'dependency_upload': 'vendor/upload/vendor/dependencies'
        }
    }, ['js/vendor/upload/upload.js'], function(App) {
        App.upload();
    });
});

2 - (这是首选方式)使用shim 配置告诉 RequireJS 任何时候请求 upload.js 时,它都需要先加载 jquery。

于 2013-09-16T15:08:53.393 回答