Search code examples
javascripttcpnetwork-programmingxmlhttprequesthandshake

When exactly does the TCP handshake occur in a XMLHttpRequest?


The XMLHttpRequest interface provides both an open() and a send() method.

In the following sample code:

var xhr = new XMLHttpRequest();
xhr.open('GET', '/server', true);

xhr.onload = function () {
  // Request finished. Do processing here.
};

xhr.send('string');

Does the TCP handshake occur when send() is invoked, or open()?


Solution

  • Only with HTTP version less than 1.1 are the lifetimes of requests and their underlying connection directly related.

    The lifetime of the HTTP request is independent of the lifetime of its underlying connection since HTTP 1.1. Many requests can be pipelined down a single connection.

    XMLHttpRequest.open is an abstraction that is convenient for the user, but under-the-hood, if the browser already has available sockets connected to the host, they can be reused, meaning that the TCP handshake happened some time ago, independently of all but the first request that passed through the connection.