Loading lessons...
HTML Server-Sent Events (SSE)
HTML Server-Sent Events (SSE)
Server-Sent Events let a website receive updates automatically from the server. Like a live scoreboard that updates by itself!
What's the idea?
Normally, your page asks the server for data ("give me this"). With SSE, the server PUSHES updates to your page automatically, whenever something changes.
Great for: live scores, stock prices, news feeds, notifications.
Create an EventSource
var source = new EventSource("demo_sse.php");
source.onmessage = function (event) {
document.getElementById("result").innerHTML += event.data + "<br>";
};
The page opens a connection, and every new message from the server appears automatically.
The server side
The server keeps the connection open and sends updates in a special format. A message looks like:
data: Hello, this is a live update!
Every line starting with data: is a message.
Checking for support
if (typeof (EventSource) !== "undefined") {
// Supported! Use it.
} else {
document.getElementById("result").innerHTML =
"Sorry, your browser does not support server-sent events.";
}
The three server events
onopen: when the connection opens.onmessage: when a message arrives.onerror: when something goes wrong.
source.onopen = function () { console.log("Connection opened"); };
source.onmessage = function (event) { console.log(event.data); };
source.onerror = function () { console.log("Something went wrong"); };
SSE vs WebSockets
- SSE: server pushes TO the page. One-way, simple.
- WebSockets: two-way: both sides can talk anytime. Good for chats and games.
TL;DR
- SSE pushes live updates from the server to your page.
- Create it with
new EventSource("url"). - Handle
onopen,onmessage,onerror. - Server sends
data: ...lines. - Use SSE for one-way live data; WebSockets for two-way.