Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to hold page render until an AJAX call completes?

Tags:

html

jquery

ajax

I know that the huge advantage of doing AJAX calls is that the rest of the page can load and be ready for the user before a certain element is quite ready yet. But I have a bit of an exceptional business requirement.

First of all, I have to use AJAX because of the architecture. Secondly, requirement is that I can't create the appearance of a delayed load of the certain section. So, I need the page to not render until the return of a jQuery AJAX call.

My only attempt so far has been to simply take the AJAX call out of the jQuery document.ready function thinking that it would then fire immediately and perhaps delay the page. This didn't work.

like image 688
Jeremy Foster Avatar asked Oct 03 '11 16:10

Jeremy Foster


2 Answers

Update 03/2015: I would strongly advise against using this method, since synchronous XMLHttpRequests on the main thread are now deprecated; see http://xhr.spec.whatwg.org/

Synchronous XMLHttpRequest outside of workers is in the process of being removed from the web platform as it has detrimental effects to the end user's experience. (This is a long process that takes many years.) Developers must not pass false for the async argument when the JavaScript global environment is a document environment. User agents are strongly encouraged to warn about such usage in developer tools and may experiment with throwing an InvalidAccessError exception when it occurs.


jQuery.ajax() sports an async parameter. When set to false, your AJAX request becomes synchronous / blocking.

As for the page load: Do not hook into any "ready" event. Just call directly after loading the jQuery library:

$('body').css('display', 'none');

Then run your (now synchronous) AJAX request.

On AJAX completion/success, Do

$('body').css('display', 'block');

Cheers.

like image 63
vzwick Avatar answered Oct 27 '22 05:10

vzwick


You can set the display of your wrapper element to none and then change it to block after the ajax request returns.

like image 42
Dustin Nielson Avatar answered Oct 27 '22 06:10

Dustin Nielson