HTML5 Server-Sent Events

published on January 31, 2012 in technical

I have just came upon another interesting HTML feature: Server-Side Events. We can now push real-time data from server to the browser. Let me show you a little example and some possible usage cases.

1. Example

First, let us create an HTML5 document:

<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div id="output"></div>
</body>
</html>

The output <div> is going to hold the server response.

Now, let us add the Javascript code to the page:

<script>
"use strict"
window.onload = function() {
    if(typeof(EventSource)!=="undefined") {
        var eSource = new EventSource("server.php");
        eSource.onmessage = function(event) {
            document.getElementById("output").innerHTML = event.data;
        };
    } else {
        document.getElementById("output").innerHTML="No support!";
    }
}
</script>

The next step would be creating a server-side script, in this case PHP script.

<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
$new_data = rand(0, 1000);
echo "data: New random number: $new_data";
flush();
exit;

This is just a simple random number generator, which doeas is perfectly for this example.

2. Possible Usages

As I see it, this possibility make the client-side code lighter. We many times need to poll servers for data, so many times repeatedly. Till now, I did this with a timer and a AJAX call. With Server-Sent Events we may do this in a more simple and elegant way.

3. Try It

I put together an example here, check it out if you wish. It works in the latest stable Google Chrome. Stable Firefox lacks support for this (at least on Ubuntu), but the Nightly has it, so it will probably be merged sometime into the stable vesion too.

It also workes on mobile Safari (Yay!)