Introduction
Building a single-page application (SPA) can often seem complex and burdensome. Typically, it involves a JavaScript framework for rendering, an API to serve JSON, and two independent codebases that must communicate effectively. This has become the norm, but it's not the only path. An alternative approach, known as HTML over WebSockets, is gaining traction.
What is HTML over WebSockets?
HTML over WebSockets proposes a method where the server sends pre-built HTML directly to the client, thereby eliminating the need to preprocess JSON in the browser. All rendering logic remains server-side, unifying the code in a single language without the need for an API. This model is often referred to as hypermedia or HTML over the wire.
Why use WebSockets?
WebSockets offer a permanent, bidirectional channel between the client and server, allowing real-time communication. Unlike HTTP or SSE (Server-Sent Events), WebSockets enable lower latency and smoother data exchange, which is essential for applications requiring real-time updates.
Origin and Use Cases
Chris McCord presented LiveView at ElixirConf 2019, demonstrating how to build a real-time Twitter clone without rendering JavaScript. Since then, this approach has inspired other implementations in various languages, such as Django LiveView for Python.
Usage Examples
- Financial Applications: Trading platforms benefit from real-time updates of market feeds.
- Online Games: Interactivity and responsiveness are crucial, and WebSockets provide a seamless user experience.
- Real-time Chat: Messaging applications can offer reduced latency and instant message updates.
How Does it Work?
While JavaScript is still used on the client side, its role is limited to establishing the WebSocket communication channel and placing the received HTML. This significantly simplifies client-side development and reduces potential rendering errors.
Advantages
- Performance: Reduced latency due to the absence of client-side rendering.
- Simplicity: Less code to maintain, a single codebase for rendering.
- Scalability: Servers can handle more simultaneous connections with reduced load.
When to Use It?
HTML over WebSockets is particularly beneficial for applications requiring instant feedback or frequent user interactions. However, for simpler applications or those where client-side rendering features are crucial, a traditional approach might still be preferred.
Conclusion
HTML over WebSockets offers a powerful and elegant alternative for developing real-time SPAs. By reducing reliance on JavaScript and centralizing rendering logic, this approach simplifies development while enhancing performance.
Let's discuss your project in 15 minutes.