简体   繁体   中英

unstable behaviour of requireJS

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 ?

The module loading is asynchronous, so if you really need jQuery loaded before the other module you have to do one of two things:

1 - Use the callback function from your require of jquery so that you don't try to load the other until jquery is loaded:

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

2 - (and this is the preferred way) use a shim configuration to tell RequireJS that any time you request upload.js it needs to load jquery first.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM