Igor Artamonov
Igor Artamonov

Reputation: 35961

RequireJS ignores some paths

I have following main.js:

requirejs.config({
    paths: {
        'backbone': 'backbone-min',
        'underscore': 'underscore-min',
        'loader': 'loader-min'
    }
})

This 'loader-min.js' file is just an optimized js from loader.js:

define(['backbone', 'underscore'], function () {
})

My HTML page contains following:

<script data-main="/js/main" src="/js/require.js"></script>
<script type="text/javascript">
   requirejs(['loader'], function(loader) {
      ....
   })
</script>

Btw, as I see from Firebug console, browser load only following urls:

GET /js/require.js
GET /js/main.js
GET /js/loader.js !!! Notice it's loader.js, not loader-min.js
GET /js/backbone-min.js
GET /js/underscore-min.js

So, the problem that for module loader it tries to load file loader.js, not path configured at main.js. Not minified/optimized file, ignoring requirejs.config value.

Most strange that it still uses correct values for backbone and underscore. Mostly, but not all time. Sometimes it fails on loading /js/backbone.js

Seems that RequireJS starts working before main.js is fully loaded and interpreted by a browser. Is it expected behaviour? or something wrong with my app?

How I can make sure that requirejs(...) function is executed only after 'main.js' is processed?

Upvotes: 3

Views: 1603

Answers (1)

Aditya Manohar
Aditya Manohar

Reputation: 2274

Your main.js file is loaded asynchronously. However this script tag (below) is parsed serially. So there is no way of predicting the order of execution (though the script below will most likely execute before the asynchronous call returns).

<script type="text/javascript">
   // require() and not requirejs()
   require(['loader'], function(loader) { 
      ....
   })
</script>

Add the require call at the end of your main.js file like this:

require.config({
// configuration.
});

require(['loader'], function(loader) { 
// callback
})

This way RequireJS is always "configured" before executing any require or define calls.

Edit: What I do typically:

<script src="/js/require.js"></script> <!-- No data-main attribute -->
<script src="/js/config.js"></script> <!-- Explicitly load configuration -->

<script type="text/javascript">
    require.config({
        baseURL: "path/to/base"
    });
    require(["module"], function(module){
        // code
    });
</script>

This way I have explicit control over what is loaded where. It also keeps my config.js file DRY.

I usually set baseURL in my bootstrap HTML because that way I can use the same config file for my Jasmine test suite.

Upvotes: 5

Related Questions