Search code examples
javascriptxmlhttprequestxmppstrophe.js

Synchronous XMLHttpRequest Strophe.js


I am using Strophe.js (JS based Xmpp library). The problem is that I need to establish synchronous connections so that the responses I receive are in the correct order. But when I use synchronous connections, the page sort of becomes stuck. Even a right-click to open the console takes minutes.

I get this warning on page:

[Deprecation] Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check https://xhr.spec.whatwg.org/.

Please help!


Solution

  • The warning just tells you that it is greatly preferred to use async calls, for a reason.

    A synchronous call will block the rest of your code until a response has been received. Somehow, it takes a long time for your synchronous call to return.

    Without looking at your code it is hard to tell why, but you could try retrieving the resource you are trying to get by typing its URL in in a browser and see how long it takes to get a response, or if you get a response at all, and if you see any errors.

    If the resource can't be retrieved or is slow in coming, you know where the problem is and where to fix it.

    There are some ways of getting XMLHttpRequest results in the right order:

    • Use synchronous calls and try to make sure the server responds fast enough;
    • Use asynchronous calls and start the next call when the previous has been returned succesfully (so start the next request in the callback of the previous one);
    • Use asynchronous calls, store a request number, store the responses in a temporary array until all the calls have returned, and sort them;
    • Some hip and modern way of doing it I don't know about but Google probably does.