Socket.io 1.3.2: client events received in browsers prior to all JS being loaded

FireFox experiences a race condition between the loading of code in scripts and receiving socket.io events if a socket establishes a connection concurrently with the loading of scripts.  If a socket.io client in FireFox connects to the socket.io server in a script, but there are socket event handlers yet to be loaded (or general JS yet to be loaded), events from the socket.io server may be received and unhandled properly on the client side due to “missing” code.  IE and Chrome tend to finish loading all JavaScript prior to handling the first socket.io event from the server, so the issue is not evident outside of FireFox.

Not documented on socket.io’s page or its GitHub page, socket.io has an “autoConnect” option on the client side initialization that helps solve this problem.  Here’s an effective connection paradigm to follow when using socket.io clients on browsers:

First, create the io Manager and initialize the socket with autoConnect = false, that way we don’t connect to the socket.io server until we set up all of our event handlers.

var socket = io('http://server_host', { autoConnect: false });</pre>
Second, set up our event handlers.
<pre class="js">socket.on('foo', function() {
  console.log('bar');
}

Finally, after all of our JS, images, frames, etc. are loaded and we are completely ready to handle all incoming socket events, follow through with connecting to the server.

window.onload = function() {
  socket.connect();
}