How Server-Sent Events Works in HTML5?

HTMLWeb DevelopmentFront End Technology

Server-sent events standardize how we stream data from the server to the client. To use Server-Sent Events in a web application, you would need to add an <eventsource> element to the document.

The src attribute of <eventsource> element should point to an URL which should provide a persistent HTTP connection that sends a data stream containing the events.

The URL would point to a PHP, PERL or any Python script which would take care of sending event data consistently. Following is a simple example of web application which would expect server time.

You can try to run the following code to learn how to use Server-Sent Events in HTML5


Live Demo

      <script type="text/javascript">
         document.getElementsByTagName("eventsource")[0].addEventListener("server-time", eventHandler, false);
         function eventHandler(event){
            // Alert time sent by the server
            document.querySelector('#ticker').innerHTML =;
      <div id="sse">
         <eventsource src="/cgi-bin/ticker.cgi" />
      <div id="ticker" name="ticker">

Finally, following is the ticker.cgi written in perl −

print "Content-Type: text/event-stream

"; while(true){    print "Event: server-time
";    $time = localtime();    print "Data: $time
";    sleep(5); }
Updated on 25-Feb-2020 06:55:09