How can you use RequireJS, and have some common JavaScript code for all pages? If I have a script tag with datamain in the template (used on all pages), can I then have a require(…) on the other pages that requires what they need? Would this cause problems with the sequence of loading? It would right? I also thought having a second script tag in the template that have all the common code (which is outside of RequireJS) hands. Is that the only approach?
Share
strong text> How can you use RequireJS, and have some common JavaScript code for
The answer to this question will help – How does RequireJS work with multiple pages and partial views?
Nope, this is fine. You can make calls to the same module if you wish and it will only be loaded once. A common example is multiple require calls all needing
jquery. You would require it each time to be sure of it’s presence, but there is no penalty as RequireJS is smart enough to fetch it just the once.Edit to answer comment:
Request jQuery and/or jQuery UI as dependencies to either define or require and the callback will execute afterwards:
This is the real fundamentals of RequireJS (requiring dependencies and executing code when they’re ready) so it might be worth having a detailed read of the documentation (which is superb).
Last thing to note, is that you will need to set a path to jQuery in your
pathsconfiguration and I’m not sure if jQuery UI registers itself as a module. If not, you’ll need to make use of theshimconfig option