How to display 'Loading' when making a 

2019-06-23 19:16发布

问题:

I want to make sure the result is shown to user, so I make synchronous AJAX call. It's quite simple to display a 'Loading' indicator with asynchronous AJAX (the examples are everywhere), but when I use synchronous AJAX call with XMLHttpRequest, the loading indicator GIF image doesn't show up at all.

Some said that it's impossible to show indicator when doing a synchronous call (block until having response from server). But I just want to ask to see whether there's a way to do it.

回答1:

It's "impossible" because Javascript is single-threaded, and the synchronous call blocks updates to the UI.

However, you may be able to display an animated 'loading' graphic before launching the synchronous AJAX call, and removing it upon success or failure. I believe most browsers will be able to continue rendering the animated gif even while technically blocked for the synchronous call.



回答2:

It is possible, see the top answer here: How to show waiting message during sync ajax call in browser

The solution is to show your loading message, hand control back to the browser, and then lock everything up with your synchronous remote call. One way to do this is to use setTimeout with a delay of zero