In your first snippet the problem is that by the time the first require
call executes, it is quite possible (quite likely in fact) that RequireJS has not yet loaded your application. The data-main
attribute initiates right away the loading of your main module but it only initiates it right away. The loading is still asynchronous. And the reason it works in your second snippet is that the outer require
forces the inner require
to execute after your main module is loaded.
So for your require
call to be successful, RequireJS must have enough information to load it. So it must already have a configuration that will allow it to find your module. This either adding some configuration before you load RequireJS. You can set require
to a configuration object which will be picked up by RequireJS when it is loaded:
<script type="text/javascript">
require = {
// Enough config to find the main module.
baseUrl: ...,
paths: ...,
bundles: {
// List here every module you want to load individually.
"app-built": ["Functions"]
}
};
</script>
<script src="/js/vendor/require.min.js"></script>
<script type="text/javascript">
require(['app-built']);
require(['Functions'], function(Functions){
console.log(Functions);
});
</script>
You don't have to pull the whole config out of your main module because RequireJS can combine configs, but there need to be enough there to allow RequireJS to start loading things. The app-built
module could contain additional configuration that is not needed for the initial steps. In the code above I've dropped data-main
and used require(['app-built'])
instead because I'm not sure whether it is possible to still use data-main
even when using the bundles
parameter. (I'm concerned it might confuse RequireJS.) Using bundles
will allow RequireJS to know that when you require Functions
, it must find it in app-built
.
Apart from perhaps still being able to use data-main
instead of the initial require
call (which I'm not sure you can do), I do not think it is possible to simplify this further.