Live events from the server side

Live updates have always been kind of a hassle — you had to deal with long polling, flash components or, if you went the HTML5 route, you'd have chosen WebSockets. That's no longer the case, you can set up EventSource in about 5 lines of code and it works over standard HTTP. One small caveat though: the client can only receive data, not send it.

Here is an example

A live updated stat of load averages on this site's server.

Holy smokes Batman, how does it work?

We created a new EventSource object with a simple var source = new EventSource(URL). This opens a long-standing connection to the specified URL (if you want to be precise about it, it closes and re-opens the connection every 60 seconds). As we want to do something with the data that's coming in, we've added an event listener to retrieve our messages. This is done with source.addEventListener("message", function(data){ ... }).

That's it basically. It's very easy as you just send text over the line and your browser handles all the resuming and error recovery for you.

Serverside we send messages over the opened connection in plain text. Each message is separated with two newline characters and consists of one or more lines of text with every line haveing a field name. The data we use for the example above looks like this:

data: [1.2, 1.3, 0.8]

The docs at the Mozilla Developer Network explain the data format pretty well.


Oh yes! The example above is just a small demo, but imagine what you could do with more "eventful" data which you offer in real-time to your visitors. It's really easy to set up on the client side, and it isn't that hard on the server side either.

So what could we do with this?

  • Create a kick-ass server monitoring application (Think of what we could do if combined with yesterday's notifications!)
  • Have live stock data displayed
  • Push live flight data to a map so you could follow an aircraft's flight path
  • Push live sports stats and other data to a visitor
  • Less useful but fun: create a live chart of tweets with the word "Xmas" in it

Great, but can I use it today?

The support for this is pretty widespread nowadays. The only browser not supporting this is IE10 (who'd have guessed?). But given that it's all plain HTTP, there are several Javascript polyfills out there to bridge the gap.

Show me the source!

Feel free to look around the differente source files we used for this example.