views:

36

answers:

1

I find myself doing this a lot:

window.onload = function(){

   $.get("http://example.com/example.html", function(data) {
       $('#contentHere').html(data);

       setTimeout("javaScriptClass.init()", 200);
   });

}

But setTimeout seems a bit hacky (and 200ms is already over three times the attention span of the average user :). What's the best alternative?

EDIT

javaScriptClass.init() acts on DOM objects from what is loaded in the ajax call

+1  A: 

I think there's some confusion here about the load, you can just do this:

window.onload = function(){    
   $.get("http://example.com/example.html", function(data) {
       $('#contentHere').html(data);
       javaScriptClass.init();
   });    
}

After the $('#contentHere').html(data); the DOM elements will be there ready to use. Also take a look at .load() for attachment (in case other onload handlers may need to attach), like this:

$(window).load(function(){    
   $.get("http://example.com/example.html", function(data) {
       $('#contentHere').html(data);
       javaScriptClass.init();
   });    
});

Though, unless you're waiting on images, this can be called in a document.ready handler and fire sooner, resulting in a better user experience.

Nick Craver
Thanks Nick. I'm befuddled but this is obviously the right answer.
Emile