I have started building a web site and have used Require.js for selectively loading scripts which I require to implement functionality. What I am experiencing is:
- the “main” script has not finished executing (or even downloading) before some of my code uses “require” to load dependencies. What this means is that the require.js config has not run and does not know the locations of my scripts.
- because the require.js config has not run by the time my code needs to use it, the “shim” mechanism has not been initialised and cannot be used.
The Common Errors page along with a lot of the issues I seem to be reading about online while trying to solve my own problems seem to suggest that this is not the right tool for the job.
This seems to be useful for single page applications or node.js applications, but not traditional sites where other scripts could be running before require.js has been initialised.
If require.js is not the right tool for the job, is there a right tool for this job? If so then what is?
Are you loading the
require.jsscript asynchronously (with anasync='async')? You want requirejs to load synchronously. Once it’s loaded, it will load further scripts, like your main.js file, asynchronously. They may all load out of order, but the code will actually get executed in the right order (respecting the declared dependencies).So in your page template, you would have this:
That will load RequireJS, and once it’s loaded it starts loading your
main.jsasynchronously. Typicallymain.jsdoes not define any modules, it just makes use of modules defined in other files. These dependencies are listed in therequire()call:The files
moduleA.jsandmoduleB.jsmust wrap their contents inside adefine(). InmoduleA.js(which depends on module C):I wonder now if you’re wrapping your modules in a
definecall. Not doing that could explain the out-of-order execution you’re experiencing.RequireJS is a perfectly valid tool on a traditional site, not just on a single-page site.