Skip to content
Advertisement

If I call function inside document ready it will not work, but if I call it on an event it works just fine [closed]

I have a java script function my_func() that i would like to call upon page loads. Here is the strange behavior that I will get: If I call the function inside the document ready it will not work:

function my_func(){
//do something
}
$(document).ready(function(){
   my_func();   
});

but if I call it on an event it works just fine:

function my_func(){
//do something
}
$(document).ready(function(){
   $('#myId').click( function(){
       my_func();
    });   
});

does anybody have any idea? how can I call it inside the document ready directly?

Advertisement

Answer

Your problem is that dijit.form.TextBox has not been loaded when the rest of the DOM has loaded. You’ll need to change your my_func code to include a call to require:

function my_func() {
    require(['dijit/form/TextBox'], function(TextBox) {
        // ...
        var newBox = new TextBox();
        // ...
    });
}

You’ll need to do this for every Dojo class. For example, if you also need dijit.form.Button:

function my_func() {
    require(['dijit/form/Button', 'dijit/form/TextBox'], function(Button, TextBox) {
        // ...
    });
}

It’s a little unfortunate that it’s this verbose, but that’s the way it goes. More information about require is available in Dojo’s documentation.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement