0

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?

LuckyLuke
  • 47,771
  • 85
  • 270
  • 434

2 Answers2

1

strong text> How can you use RequireJS, and have some common JavaScript code for

all pages?

The answer to this question will help - How does RequireJS work with multiple pages and partial views?

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?

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:

require(['jquery', 'jquery-ui'], function($) {
    // jQuery is passed in as first argument but as jquery-ui
    // merely augments jQuery we don't need it as the second argument
});

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 paths configuration and I'm not sure if jQuery UI registers itself as a module. If not, you'll need to make use of the shim config option

Community
  • 1
  • 1
Simon Smith
  • 8,024
  • 2
  • 30
  • 40
  • Okey. How is it possible to control that jquery, jquery UI etc is loaded before my own script? Now my script is loaded between jquery and jquery UI causing it to fail. – LuckyLuke Nov 27 '12 at 14:05
0

Create your file and put the code inside it like this

    define(function () {
            this.myProp = '';
    }) 

Set the path to the file in your requirejs.conf

    path { myfile: 'js/myfile'} 

You can now load it like this

require([myfile], function (myfile) {
    console.log(myfile.myProp)
})
AlexandruSerban
  • 312
  • 2
  • 9