1

I often start my JavaScript apps like this:

jQuery(function($) {
    ... code for the app ...
});

I'm just starting to use RequireJS, and will start the app like this:

define(['jquery'], function($) {
    ... code for the app ...
});

Now, as I don't want the app to start processing until all the HTML has been loaded, I've combined the two like this:

require(['jquery'], function($) {
    $(function($) {
        ... code for the app ...
    });
});

Is that the way to do it?

Marc Rochkind
  • 3,678
  • 3
  • 30
  • 38

3 Answers3

0

The RequireJS documentation touches on this and offers has a slightly more convenient option:

require(['domReady!'], function (doc) {
    //This function is called once the DOM is ready,
    //notice the value for 'domReady!' is the current
    //document.
});

Note that you will need to download the domReady plugin, and if you have a very complex page you may wish to use the "explicit function call" method that they also show... Although then it looks an awful lot like what you're already doing with jQuery.

Darien
  • 3,482
  • 19
  • 35
0

So the main diferences between define and require in this scenario is, one declare a module and the second one call this defined module, then if it is not loaded, the browser download the js library.

To take control about when your require files will download, you need to use the domReady plugin.

You need to put the js library at you require.config, I usually put at the same directory as declared at the baseUrl property, for example:

require.config({
    baseUrl: "js/lib",
    paths:{
        filter:"../src/filter",
        addPanel: "../src/edit-panel"
    }
}

I put the domReady.js at the js/lib/ folder.

So, then you can use the require method at any place of you html file:

require(['jquery!'], function ($) {

}); 

Note that I use the symbol ! to indicate that this library is load after the completely page load.

Claudio Santos
  • 1,307
  • 13
  • 22
0

As the box at the top of the page, my question is answered here:

Requirejs domReady plugin vs Jquery $(document).ready()?

The other answers here essential repeat what's in the above link. But, thanks!

Community
  • 1
  • 1
Marc Rochkind
  • 3,678
  • 3
  • 30
  • 38