Dojo addOnLoad, but is Dojo loaded?

adamrice32 picture adamrice32 · Jan 21, 2009 · Viewed 12.2k times · Source

I've encountered what seems like a chicken & egg problem, and have what I think is a logical solution. However, it occurred to me that others must have encountered something similar, so I figured I'd float it out there for the masses.

The situation is that I want to use dojo's addOnLoad function to queue up a number of callbacks which should be executed after the DOM has completed rendering on the client side. So what I'm doing is as follows:

<html>
    <head>
        <script type="text/javascript" src="dojo.xd.js"></script>
        ...
    </head>
    <body>
        ...
        <script type="text/javascript">
            dojo.addOnLoad( ... );
            dojo.addOnLoad( ... );
            ...
        </script>
    </body>
</html>

Now, the issue is that I seem to be calling dojo.addOnLoad before the entire Dojo library has been downloaded the browser. This makes sense in a way, because the inline SCRIPT contents should be executed before the entire DOM is loaded (and the normal body onload callback is triggered).

My question is this - is my approach sound, or would it make more sense to register a normal/standard body onload JavaScript callback to call a function, which does the same work that each of the dojo.addOnLoads is doing in the SCRIPT block. Of course, this begs the question, why would you ever then use dojo.addOnLoad if you're not guaranteed that the Dojo library will be loaded prior to using the library?

Hopefully this situation makes sense to someone other than me. Seems like someone else may have encountered this situation.

Thoughts?

Best Regards, Adam Rice

Answer

Maine picture Maine · Jan 23, 2009

You're doing it correctly. External Javascript files are loaded and executed synchronously in order, so by the time it reaches your dojo.addOnLoad( ... ); Dojo has loaded. Use dojo.addOnLoad instead of window.onload for two reasons:

  • it fires earlier, because it utilizes DOMContentLoaded
  • it handles asynchronous loading of dojo.require by postponing the execution until all required scripts have been read

Explained in DojoCampus as (dojo.addOnLoad):

dojo.addOnLoad is a fundamental aspect of using Dojo. Passing addOnLoad a function will register the function to run when the Dom is ready. This differs slightly from document.ready and body.onload in that addOnLoad waits until all dojo.require() (and their recursive dependencies) have loaded before firing.