Why You Should Use XMLHttpRequest Asynchronously

Why You Should Use XMLHttpRequest Asynchronously


Synchronous XMLHttpRequest Blocks the UI Thread

We already know performing a blocking operation on a UI thread is asking for trouble. We’ve blogged about this before. It might not be apparent, but this is exactly what can happen when calling the XMLHttpRequest.send() method synchronously (i.e. passing false for bAsync when calling the open method). The UI thread has to wait until it gets a response from the server, or until the request times out. While waiting, it’s not pumping messages.

Why Use Synchronous XMLHttpRequest At All?

Developers tend to use synchronous over asynchronous is because it’s easier and can many times lead to less complex code. This StackOverflow thread states some potentially valid opinions on why you’d use one over the other, but nothing compelling enough that makes it worth the risk.

Fixing It…

There are at least two ways you can write your code to avoid these hangs. The first method is preferred, because you won’t block on the UI thread. The second is less than optimal, because you’ll still block, but for less time than you’re probably doing now.

  1. Write your code to call open asynchronously.
    You need to pass true for the bAsync parameter to the open method, and you need to write an event handler for the onreadystatechange event. There are many examples of how to do this out one the web, like this one.
  2. Set the timeout property.
    Because the Desktop Window Manager detects a hang after 5 seconds of unresponsiveness, and IE9 Hang Resistance after 8, I would set the timeout property to something under 5 seconds. You may also want to consider creating a function to handle the ontimeout event.
    (How did I get these numbers? Refer to here and here respectively – also already mentioned above)
This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s