Svelte and Svelte-kit — Rendering
In the previous post, we learnt few of the reasons why Svelte and Svelte-kit is a good idea. One of the reasons is about better performance due to better rendering. This post is about how a WebApp can be rendered in order to optimise performance and user experience.
Rendering a WebApp plays an important role when it comes to its performance. The Svelte apps can be rendered in three different ways:
Client-Side Rendering (CSR):
This is the traditional way in which the WebApps were rendered. The browser gets the whole WebApp from the server in a shot. The browser then renders the different sections as and when the request or interaction is made. This method has the overhead on the browser to change DOM elements but at the same time, it is light on the network data. Though it works best when a lot of offline data is required, it is not very optimal when it comes to places where the DOM changes a lot. It is very useful or optimal when it comes to Single Page Applications (SPA).
Server-Side Rendering (SSR):
This is typically how the React WebApps started rendering. Though the WebApp is sent to the browser, the server keeps rendering the different pages as and when the interaction or request is made. The server keeps the overhead of computations instead of the browser. Hence, the browser performance gets improved. But the overhead remains in the form of network performance. The requests to the server and the response back from the server ends up using a lot of network data. This, however, can be reduced by using service workers. Service workers keep network data in browser cache to re-use as and when required, reducing network traffic. React started this rendering to reduce overhead on the browser. This is mainly useful when the DOM changes are not very often but the WebApp has multiple pages.
Hydrated Rendering:
This is the technique that is commonly used by Svelte. In this method, the browser is sent most of the data from the server, but the browser makes a few computations instead of sending all interactions to the server. The browser send the requests to the server, which sends the response. The browser then injects this data sent directly to the DOM elements. The browser converts the static page sent by the server to a dynamic one by adding event handlers to the elements. This is optimised hybrid of both client-side and server-side rendering, containing the best of both worlds.