Dojo: dojo/domReady! vs dojo/ready

Dojo, my javascript library of interest these days, has one stumbling block for beginners, the distinction between dojo/domReady! plugin and dojo/ready module.

dojo/domReady! is used in all the examples and is considered equivalent of jquery.ready method.

This:

$(function() {
    console.log("DOM ready");
});

is equivalent to:

require(["dojo/domReady!"], function() {
    console.log("DOM ready");
});

The problem is that dojo has a concept of modules that can be loaded on demand, and dojo loads them asynchronously, which means your application initialization has to wait for DOM to get ready, as well as wait for all modules to become available.

For this functionality, there is "dojo/ready". Equivalent code would be:

require(["dojo/ready"], function(ready) {
    ready(function(){
        console.log("DOM is ready and all required modules are loaded");
    });
});

One of the common beginners error in dojo is using "dojo/domReady!" when using dojo\'s declarative syntax. Widgets that are initialized by declaring them in HTML, they "become available" after "dojo/parser" and widgets referenced in HTML are loaded. Further "dojo/parser" first waits for DOM to become available, and then it starts processing the HTML. When using domReady!, the callback is called while parser is doing its thing, and widgets may not be ready yet.

So which to use? "dojo/domReady!" is slightly less code, and slightly more "aesthetic", and may be used when doing something complex, and not using dijit widgets, or relying on dojo\'s autoparser. For anything else use "dojo/require".

Here is an interesting thread on dojo\'s mailing list about this.


Published: Sep 26 2012

 
0 Kudos
blog comments powered by Disqus