1
// Load the dom module
require(["dojo/dom"], function(dom){
});

I understand that the function is called when the dom module is loaded but I am not clear with what will be the code within the function. Is it a container for all the javascript code on my page?

sly_Chandan
  • 3,437
  • 12
  • 54
  • 83

1 Answers1

7

The function is callback, that the AMD loader will call when it has loaded all the modules that you require.

If I have

require(["dojo/_base/ready", "dojo/_base/declare"], function(ready, declare) {

  // do something with declare and ready

});

AMD is going to load ready and declare. This may require AMD to make an asynchronous call back to the server. Once AMD has loaded the modules, it calls the function you passed into the require method.

My answer at Dojo Builds...? What now? has some more details on the AMD API.


Answer to the question in the comment. The following two statements could be anywhere on the page.

<script type="text/javascript">
require(["dojo/_base/ready", "dojo/_base/declare"], function(ready, declare) {
   // do something with declare and ready
});
</script>

<script type="text/javascript">
require(["dojo/_base/ready", "dojo/_base/declare", "dijit/form/Button"], 
   function(ready, declare, Button) {
     // Assuming this is the second statement to be executed, AMD will 
     // realize that ready and declare have previously been loaded,
     // so it will use the previously loaded modules, load the Button module, 
     // and then execute the callback

     // do something with declare, ready, and Button
});
</script>
Community
  • 1
  • 1
Craig Swing
  • 8,152
  • 2
  • 30
  • 43
  • If both the modules are loaded then only one function will be executed? – sly_Chandan Feb 28 '13 at 15:45
  • Yes. You can read the require method call as "these are the modules I need. When you (AMD) load them, this is what(the function) I want to do. – Craig Swing Feb 28 '13 at 15:56
  • But my page will have many tasks to be done. So will I have to require same modules again and again for different tasks? – sly_Chandan 5 mins ago – sly_Chandan Feb 28 '13 at 16:09
  • You can and AMD will realize the module is already loaded and move on to loading other modules. If all the modules were previously loaded, then the callback function will be called. – Craig Swing Feb 28 '13 at 16:14
  • Can you show me an example with previous loaded modules and new modules loaded with callback function – sly_Chandan Feb 28 '13 at 16:17
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/25301/discussion-between-sly-chandan-and-craig-swing) – sly_Chandan Feb 28 '13 at 16:35