How to get some revealing module code to only run after DOM ready?-Collection of common programming errors

I believe what you’re looking for is something like this:

notice the difference between these two examples:

//working
var myNamespace = (function($) {
    $(function(){
        var init = (function(){
            var text = document.createTextNode("Everything's ready!");
            document.body.appendChild(text);
        })();
    });

}(jQuery));

//Error: Cannot call method 'appendChild' of null 
var myNamespace = (function($) {

        var init = (function(){
            var text = document.createTextNode("Everything's ready!");
            document.body.appendChild(text);
        })();


}(jQuery));

Though, what’s happening here is that init() is effectively not accessible by anything else within the namespace, because it’s taking place after the DOM has loaded.

Nonetheless, this is close to what you’re having a problem with, I think…

I’m assuming that you want the DOM ready wrapper within your module for organizational purposes.

Also note that you have access to the module as you would normally from outside of the module:

//appends to the body: "Everything's ready!undefined
var myNamespace = (function($) {
   var private = " Hello world";
        $(function(){
            var hello =(function(){
                var text = document.createTextNode("Everything's ready!" +myNamespace.private);
                document.body.appendChild(text);
            }());
        });

    return{
        public: " Hello World"   
    }

}(jQuery));



 //works as expected 
    var myNamespace = (function($) {    
     var private = " Hello world";
     $(function(){
      var hello =(function(){
       var text = document.createTextNode("Everything's ready!" +myNamespace.public);
       document.body.appendChild(text);
      }());
     });

     return{
      public: " Hello World"   
     }   }(jQuery));

Originally posted 2013-11-09 22:47:07.