3

I have an AJAX call I'm making. It's synchronous so it 'hangs' while the content loads. Before the AJAX call I append a preloading image to the soon-to-be parent node of the incoming content:

function makePreLoader( parentNode )
{
  var img = document.createElement( "img" );
  img.src = "images/preloader.gif";
  parentNode.appendChild( img );
}


function getData( )
{
  var parentNode = document.getElementById( "myParentNode" );
  makePreloader( parentNode );

  $.ajax( 
    "http://www.example.com/",
    {
      success: function( resp )
      {
        $( parentNode ).html( resp );
      },
      async: false
    }
  );
}

My script at example.com is a simple php script that hangs 7 seconds and then replies "done".

When I call 'getData' the expected behavior is to see the preloading image load, and then it should be replaced by "done".

The actual behavior is the call hangs (apparently without appending the preloader) and then loads the content.

Has anyone had a similar issue? Can someone recommend a good solution?

KeatsKelleher
  • 9,063
  • 4
  • 41
  • 47

2 Answers2

5

use ajaxStart instead

here is an example how to do it

https://stackoverflow.com/a/68503/413670

Community
  • 1
  • 1
Rafay
  • 30,236
  • 5
  • 64
  • 98
0

There isn't a good solution, except to make the call asynchronous. A synchronous Ajax call, by definition, blocks the UI thread. Hence all operations on the UI gets suspended till the call responds. Thats why it seems like the UI is hung.

tl;dr: Use asynchronous ajax. There are few, if any, good reasons you should do sync calls.

Rakesh Pai
  • 24,847
  • 3
  • 23
  • 29
  • There are a number of reasons to use synchronous AJAX calls. If you're initializing a fat client for a particular user, for example, and the initialization is dependent on some data specific to the user. The alternative would be to delay initialization by polling for the AJAX response using setTimeout/return to restart some dependent portion of the initialization. This adds significant complexity and, less notably, overhead associated with the polling, albeit very little (since you can control the resolution of the timeout to the millisecond). – KeatsKelleher Dec 08 '11 at 16:47