RobertPitt
RobertPitt

Reputation: 57268

XHR Bandwidth reduction

So were using XHR to validate pages exists and they have content, but as we do a lot of request we wanted to trim down some of the bandwidth used.

We thought about using a HEAD request to check for !200 and then thought well that's still 2 request's if the page exists and then we come up with this sample code

Ajax.prototype.get = function (location, callback)
{
    var Request = new XMLHttpRequest();

    Request.open("GET", location, true);
    Request.onreadystatechange = function ()
    {
        if(Request.readyState === Request.HEADERS_RECEIVED)
        {
            if(Request.status != 200)
            {
                //Ignore the data to save bandwidth
                callback(Request);
                Request.abort();
            }
            else
            {
                //@Overide the callback here to assure asingle callback fire
                Request.onreadystatechange = function()
                {
                    if (Request.readyState === Request.DONE)
                    {
                        callback(Request);
                    }
                }
            }
        }
    }
    Request.send(null);
}

What I would like to know is does this actually work, or does the response body always come back to the client.

Thanks

Upvotes: 0

Views: 494

Answers (1)

Martin Thurau
Martin Thurau

Reputation: 7654

I won't give a definitve answer but I have some thoughts that are to long for a comment.

Theoretically, a abortion of the request should cause the underlying connection to be closed. Assuming a TCP based communication that means sending a FIN to the server, which should then stop sending data and ACKs the FIN. But this is HTTP and there might be other magic going on (like connection pipelining, etc.)...

Anyway, when you close the connection early, the client will receive all data that was send in communication delay as the server will at least keep sending until he gets the the STOP signal. If you have a medium delay and a high bandwith connection this could be a lot of data and will, depending on the amount of data, most likely be a good portion of the complete data.

Note that, while the code will not receive any of this data, it will be transferred to the network device of the client and will be at least passed a little bit up the network stack. So, while this data never receives you application level, the bandwith will be consumed anyway.

My (educated) guess is that it will not save as much as you would like (under "normal" conditions). I would suggest that you do a real world test and see if it is worth the afford.

Upvotes: 1

Related Questions