KeatsKelleher
KeatsKelleher

Reputation: 10191

Load preloader before AJAX call

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?

Upvotes: 3

Views: 19546

Answers (2)

Rakesh Pai
Rakesh Pai

Reputation: 26277

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.

Upvotes: 0

Rafay
Rafay

Reputation: 31043

use ajaxStart instead

here is an example how to do it

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

Upvotes: 5

Related Questions