Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any reason to use a synchronous XMLHttpRequest?

It seems most everyone does asynchronous requests with XMLHttpRequest but obviously the fact that there is the ability to do synchronous requests indicates there might be a valid reason to do so. So what might that valid reason be?

like image 363
Darrell Brogdon Avatar asked Jan 18 '10 18:01

Darrell Brogdon


People also ask

Why is synchronous XMLHttpRequest deprecated?

Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience.

Is XMLHttpRequest synchronous or asynchronous?

XMLHttpRequest supports both synchronous and asynchronous communications. In general, however, asynchronous requests should be preferred to synchronous requests for performance reasons. Synchronous requests block the execution of code which causes "freezing" on the screen and an unresponsive user experience.

What is the purpose of XMLHttpRequest?

XMLHttpRequest (XHR) objects are used to interact with servers. You can retrieve data from a URL without having to do a full page refresh. This enables a Web page to update just part of a page without disrupting what the user is doing. XMLHttpRequest is used heavily in AJAX programming.

What is difference between synchronous and asynchronous requests?

Synchronous request — (Default) Where the client blocks and waits for the result of the remote request before continuing execution. Asynchronous request — Where the client continues execution after initiating the request and processes the result whenever the AppServer makes it available.


2 Answers

Synchronous XHRs are useful for saving user data. If you handle the beforeunload event you can upload data to the server as the user closes the page.

If this were done using the async option, then the page could close before the request completes. Doing this synchronously ensures the request completes or fails in an expected way.

like image 200
Sami Samhuri Avatar answered Oct 01 '22 03:10

Sami Samhuri


I think they might become more popular as HTML 5 standards progress. If a web application is given access to web workers, I could foresee developers using a dedicated web worker to make synchronous requests for, as Jonathan said, to ensure one request happens before another. With the current situation of one thread, it is a less than ideal design as it blocks until the request is complete.

like image 26
D.C. Avatar answered Oct 01 '22 03:10

D.C.