Science Knowings: HTML Course For Social Media

HTML5 Server-Sent Events API

Introduction to HTML5 Server-Sent Events API

From Web Workers to Server-Sent Events!

In this session, we'll dive into HTML5 Server-Sent Events (SSE), a powerful technology for building real-time web applications.

What are Server-Sent Events (SSE)?

Server-Sent Events (SSE) is a technology that allows a web server to push data to a web client in real-time, without the need for constant polling from the client.

Benefits of Using SSE

  • Real-time data updates
  • Reduced server load
  • Improved user experience
  • Easy to implement

How SSE Works: A Step-by-Step Guide

  1. Server sends an initial response with Content-Type: text/event-stream.
  2. Server sends data events as they occur, using event: message.
  3. Client receives events using EventSource API.

Setting Up SSE on Your Web Server

header('Content-Type: text/event-stream');
echo 'event: message
data: Hello, world!


Creating an SSE Client

const eventSource = new EventSource('/sse');
eventSource.onmessage = (e) => { console.log(; };

EventSource API: Receiving Events in JavaScript

eventSource.addEventListener('message', (e) => { console.log(; });

Handling SSE Events: Event Listeners

  • onmessage: Triggered when a message event is received.
  • onerror: Triggered when an error occurs.
  • onopen: Triggered when the connection is opened.

Handling Server Errors in SSE

eventSource.onerror = (e) => { console.error(e); };

Real-Time Applications with SSE

SSE is ideal for applications that require real-time updates, such as:

  • Live chat
  • Stock market updates
  • News feed updates

Live Chat with SSE

const chatBox = document.getElementById('chatbox');
eventSource.onmessage = (e) => { chatBox.innerHTML += + '
'; };

Stock Market Updates with SSE

const stockTicker = document.getElementById('stock-ticker');
eventSource.onmessage = (e) => { stockTicker.innerHTML =; };

News Feed Updates with SSE

const newsFeed = document.getElementById('news-feed');
eventSource.onmessage = (e) => { newsFeed.innerHTML += + '
'; };

Next Topic: HTML5 Page Visibility API

In our next session, we'll explore the HTML5 Page Visibility API, which provides information about the visibility state of a web page. Follow us to learn how to create responsive and user-friendly web applications.