user3949359
user3949359

Reputation:

Why do we have to load the data-main twice in require.js?

We specified the file containing the modules once in data-main, and then we required the file once again in the script. We're "importing" it twice this way. What is the point in doing so?

<script src="js/require.js" type="text/javascript" data-main="js/main"></script>
<script type="text/javascript">
   require['main'], function () {
     //load this page, once "main" has been loaded
     require['something'];
}
</script>

Upvotes: 1

Views: 715

Answers (2)

luxas
luxas

Reputation: 438

From http://requirejs.org/docs/api.html#data-main:

If you want to to do require() calls in the HTML page, then it is best to not use data-main. data-main is only intended for use when the page just has one main entry point, the data-main script. For pages that want to do inline require() calls, it is best to nest those inside a require() call for the configuration:

<script src="scripts/require.js"></script>
<script>
require(['scripts/config']), function() {
    // Configuration loaded now, safe to do other require calls
    // that depend on that config.
    require(['foo'], function(foo) {

    });
});
</script>

So, if you have some config to do, these options are available:

  1. Set all logic to a config file and load it via data-main.
  2. Make an inline script and require two times as in the example.

Happy coding and feel free to ask for more info!

EDIT: The inline script content can be exactly the same as the data-main referenced file's content.

In fact, when RequireJS has loaded it makes an script of the path (with the async attribute).

So, the choice is yours, inlined or external.

One more thing, the first require in the example, loads only config. I think it's bad practise but if you have to, you can skip the first require and instead copy the config in front of the second require.

Hope it helps! :)

Upvotes: 1

Surender
Surender

Reputation: 757

As per documentation http://requirejs.org/docs/api.html#data-main, first script including will trigger load of main.js. Before the load of main.js, the second script tag may get executed and since configuration is not loaded yet it may fetch fetch wrong file. In your case you are explicitly asking it to execute your script when main.js has loaded. Excluding the data-main attribute on script tag would have been fine here.

Upvotes: 0

Related Questions