Detect when XMLHttpRequest has connected

2.2k views Asked by At

I'm trying to detect when a long-running XMLHttpRequest has actually connected to the server.

Right now, when I listen for the readystatechange event, it only fires when the request is finished. My test server sends the headers and some data, and after a long timeout (10s), it finishes the request. The XHR only fires events at the very end, and then it does one for each of the following states back-to-back: HEADERS_RECEIVED, LOADING, DONE.

Here is my browser code:

var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.onreadystatechange = function(evt) {
    console.log('Request is now in state ' + xhr.readyState);

    if(xhr.readyState === xhr.HEADERS_RECEIVED) {
        console.log('Request has started');
    }
    if(xhr.readyState === xhr.DONE) {
        console.log('Request is finished');
    }
};
xhr.send(null);

How can I detect when the headers have ACTUALLY been received? I'm assuming that I can't detect when the request starts, based on what's available in the API.

So far, I've come up with the following:

  • Set request method to POST
  • Send some data when the request is opened e.g. xhr.send('something')
  • Listen for the xhr.upload.onload callback

Like this:

xhr.upload.onload = function(evt) {
    console.warn('Request has started');
};

This only works in Firefox and Safari though. Not Chrome or IE.

1

There are 1 answers

2
epascarello On

The XMLHttpRequest object has 5 readystates

  • 0 = uninitialized
  • 1 = loading
  • 2 = loaded
  • 3 = interactive
  • 4 = complete

You are just checking two of them in your code. Also you should be using an else if for efficiency.