Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call a function before synchronous call

I have a simple question (but the answer does not seem to be simple).

I have a synchronous AJAX call in my code and I want to call a function before this synchronous call.

The function I want to call is simply

$.blockUI();

from jQuery BlockUI Plugin.

I simply tried to put that line before my $.ajax call but the blockUI seems to be called after the synchronous call.

I then tried to use the beforeSend option of $.ajax, same problem as above.

Thanks in advance for any answer you could bring (except using asynchronous call which is just impossible in my case...)

Code is available here : http://jsfiddle.net/vWsus/2/

like image 389
user1374021 Avatar asked Jul 24 '12 14:07

user1374021


2 Answers

Synchronous calls are bad, they lock up the browser and if the call is not returned, it is not a good user experience. The problem you have is the synchronous call is locking up the browser so the DOM never has time to redraw. You need to give time for the DOM to update, so set a timeout before making the Ajax call.

$.blockUI({ message: '<p>foo</p>' });
window.setTimeout( ajxCallFnc, 100);
like image 72
epascarello Avatar answered Sep 25 '22 14:09

epascarello


In your case, it's not that the blockUI is called after the synchronous call, it's just that the synchronous request prevents the display reflow (which generally happens "sometimes later" than your actual DOM manipulation). And as you said, when you tried & called blockUI before the call to ajax rather than from inside the beforeSend callback, you end up with pretty much the same result.

There is nothing that can be done in jQuery to prevent this behaviour since it is not a jQuery bug (nor a browser one per se, seeing as synchronous xhr requests are supposed to freeze the browser anyway and that nothing says the browser has to carry on with the reflow in that instance).

All I can recommand is to NEVER EVER use synchronous requests. Asynchronous ones are easy enough to deal with.

You can take a look on Why You Should Use XMLHttpRequest Asynchronously

like image 38
M. Abbas Avatar answered Sep 23 '22 14:09

M. Abbas