Loaders can be made asynchronous and be awaited in the front-end. By doing so, they can be streamed into the frontend.

Important background knowledge:

  • top level promises are awaited
  • nested promises are streamed

Code example

export const load: PageServerLoad = async (event) => {
// this function can then be streamed in: 
  const getMessage = async () => {
    await delay(3000)
    return { message: "hello"}
  }
  
 
return {  message: getMessage() };

The await should be at the bottom, as it will block other loadings.

Await it in the client: {#await data.message}

What does this do?

While a usual response from the server might look like this:

<html>
	<body>
	content
	</body>
</html>

When using streaming, the server keeps the connection open while step-by-step sending the page’s content:

<html>
	<body>
	content
	</body>
</html>
<!-- streamed-in later: --> 
<script>{}</script>

In this example, the HTML-body is sent first, so the browser can render it. After this, a script can be streamed and executed, rendering additional content on the page.

This can be used to render content, which takes longer and would block the server’s response (e. g. a huge database query)

TL;DR: Use it make your page load faster, when having content that is fine to load after the users sees the website for the first blink.

Support

As this utilizes the concept of Streaming HTTP responses, this feature isn’t necessarily supported everywhere. Make sure to check if your HTTP proxy, runtime edge server or serverless provider supports this feature before rebuilding your Loaders

Resources