April 10, 2012

Merging $.get and $.ready

Question by cwolves

Put simply I have an ajax call that sometimes completes before the page is loaded, so I tried wrapping the callback in $( fn ), but the callback doesn’t fire if the page is loaded… Anyone have a good solution to this?

$.get( '/foo.json', function( data ){
    $( function(){
        // won't get here if page ready beats the ajax call

        // process data
        $( '.someDiv' ).append( someData );
    } );
} );

And yes, I know that if I flipped the order of those it would always work, but then my ajax calls would be needlessly deferred until the document is ready.

Answer by Bergi

No, functions which are added to onDOMready will always be executed, and will instantly be executed if the event has already happened. See the docs at http://api.jquery.com/ready/: Only if you would use $(document).bind("ready") it will not get executed when the event had already fired.

A possible reason for non-firing event handlers are other handlers throwing an error. jQuery has an internal array for to-be-executed handlers, and the method which handles the native DOM load event just iterates over it. If one of the earlier handlers rises an error, the loop breaks and other handlers added afterwards will not be invoked.

Answer by Starx

It wont hurt to do this.

var getData;
$.get( '/foo.json', function( data ){
    getData = data;
});
$(function() {
    var intt = setTimeinterval(function() {
         if(getData.length) {
              //do your task
              clearInterval(intt);
         }
    }, 100);
});
...

Please fill the form - I will response as fast as I can!