title: The mechanics of the JavaScript WebSockets API
body: <p>I've been trying to understand some code used to open a websocket:</p>
  
  <pre><code>var ws = new WebSocket('ws://my.domain.com');
  ws.onopen = function(event) {
      ...
  }
  </code></pre>
  
  <p>My question is how does the handshaking get started?  If it is started in the WebSocket constructor, then how does onopen get called if it isn't set by then?  If the WebSocket constructor creates a thread that does the handshaking, then does onopen have to be defined quickly enough before the handshaking is over?  If so, that sounds a little dangerous because if the JS virtual machine is slowed the handshaking could be finished before onopen is defined, which means that the event is not handled.  Or does setting the onopen function trigger the handshaking?</p>
  
  <p>Could someone explain to me the mechanics of the API please?</p>