Login Register

Error while trying to add dojo programmatically to the DOM

Hi;

I have to load the dojo libraries programatically, but when I try this, I get the warning (from Firebug) that dojo is not defined. Here is some code:

dojolib = document.createElement('script');
dojolib.setAttribute("type","text/javascript")
dojolib.setAttribute("src", "/js/dojo/dojo/dojo.js");
dojolib.setAttribute("djConfig","parseOnLoad: true");
document.getElementsByTagName("head")[0].appendChild(dojolib);

// later on...

dojo.require(dojo.parser); // throws an error

The exact same code worked well when I was able to use the standard tag to load the libraries.

Any tips would be appreciated!

thanks
-s

You can try the

You can try the djConfig.afterOnLoad flag to do this behavior (in Dojo 1.1 or later). See this test page for an example:
http://archive.dojotoolkit.org/nightly/dojotoolkit/dojo/tests/_base/_loa...

There was a bug fix after Dojo 1.1 for this behavior, I think related to dijits that had localization bundles, so while this might work better, you still may see an issue until 1.2 comes out, depending on what code you dojo.require into the page.

No, that's not the same thing

When you add the script by a tag, the browser waits to load the file and parse it before continue the execution, when you add the file by means of a DOM node, the browser adds the tag and continue the execution without wait for the file finishes load and parse (this is the javascript on demand technique, used by dojo on its io.script object). So, you cannot be sure that the file was loaded when the "dojo.require..." instruction executes and in several cases it'll fire a JS error. Question, why are you loading the Dojo library on demand?

Loading Dojo on demand can

Loading Dojo on demand can help if you have a progressively enhanced site that uses JS for just some small things that are not needed immediately on page load. By delaying the loading of Dojo, your page will appear quicker to the user.

In Dojo 1.2, this has been made easier with the djConfig.afterOnLoad, djConfig.require and djConfig.addOnLoad options -- you can use djConfig.require to avoid the script error dasaev mentioned, and you can use djConfig.addOnLoad to register a function to fire once dojo and any dojo.required modules load:

djConfig = {
    afterOnLoad: true, //Tells Dojo to not wait for onload event, just start initializing
    require: [
        "dijit.form.Button",
        "dojo.parser"
    ],
    addOnLoad: function(){
        //Do something once Dojo, dijit.form.Button and dojo.parser load.
    }
}