Reputation: 25321
What determines how early Require.js loads what ever files are required? Is loading executed as soon as the script is executed? After DOMContentLoaded? Something else?
I'm profiling a page I want to optimize and one thing I notice constantly is that Require fires off noticeably later than other scripts, what could be the reason?
Upvotes: 0
Views: 1233
Reputation: 10518
JRBurke hangs out around here sometimes, so he would be able to answer better than I will, because I'm just going to make some assumptions.
It sounds like you're using multiple script tags in your page, so if I had to guess I would say that the RequireJS dependency is simply loading later than other script tags. Here's a whole bunch of info on the load and execute order of script tags.
Otherwise, my understanding of RequireJS is that it loads things as they are needed. Imagine your RequireJS tag looks like this:
<script src="lib/require.js" data-main="main.js"></script>
If your main.js
file looks like this:
requirejs.config({ /*conf */ });
Then RequireJS loads the main file, which configures RequireJS, and does nothing more. Later, maybe one of your files looks like this:
/* code, code code */
require(
['dist/module'],
function( distModule ){
/* code code code */
}
);
At this point, Require would start firing off requests to resolve any dependency chains for dist/module
. If any code before this introduces a delay (like waiting for something to load, or if it's wrapped in a jQuery DOMReady), RequireJS won't start loading modules until all those delays have resolved.
My situation is a little different, and it might provide some insight. I have only one script tag in my entire application:
<script src="vendor/require.js" data-main="build/app"></script>
My main file looks like this:
requirejs.config({ /*conf */ });
require(
['dist/module1', 'dist/module2'],
function( distModule1, distModule2 ){
/* code code code */
}
);
distModule1
and distModule2
kick off loading the ENTIRE application, and would fire off every request to get what it needs for the main view. As I move around the application, it fires off a request to get what it needs for subsequent views. I've actually used the r.js whole-project optimizer to compile everything into that one single file, so as soon as it loads, the entire application is loaded (300kb or so).
In summary, the RequireJS library is loaded as soon as the browser encounters the script tag. Code loaded this way is executed immediately. Assuming I understand RequireJS correctly, the library will then immediately attempt to load the data-main
file - and I believe this is done asynchronously.
Every time a module is encountered, RequireJS loads them asynchronously. Any delay you're seeing might be related to that.
Upvotes: 1