Looking for a way to flush Razor pages early

With Asp.Net MVC it is possible to flush out the header section of any page before sending the body. This is useful to instuct the browser to already start downloading linked CSS (an possible) JS files.

An example of how to do this can be found here:

I would like to implement the same thing for ServiceStack Razor (.Net Core) but I cannot find where to plug this in to… Any handlers would be appreciated, provided this can be done at all.

ServiceStack.Razor uses MVC under the hood so you have access to their APIs in the base Razor views. The only place I can see is calling FlushAsync() in your master page just after </head>:

</head>
@{
    await base.FlushAsync();
}

Although flushing before the entire response is known would need to be sent with chunked encoding since the Content-Length of the page is unknown.

1 Like

OK, will try this. Chunked is perfect. If this works, JS and CSS files can be downloaded before content is sent. Thx.

....
</head>
@{ 
  await base.FlushAsync();
  await Task.Delay(5000); // wait a bit (the external resources are loaded by client)
}
<body>
...

This sends the header straight away and the webbrowser starts downloading any CSS and JS files as specified in the header. Since all resources are loaded before the page is served, this allows for instant rendering. Thanks again!

Implemented it on this live website: https://www.gratisaftehalen.nl
100% ServiceStack on .Net Core :smile:

1 Like

5 seconds seems like a long time to wait no?

Otherwise it’s looking pretty good, except there’s some jankiness when each payload when the content loads (from NJ), it doesn’t look like it can calculate the exact size of the banner ad. I’d look at doing something like seeing if you can embed the ad in a fixed sized layout to avoid the layout reflow when the ad loads.

Relevant: I watched a pretty good talk on optimizing for the time to first meaningful paint which talks about different options for pre-loading critical resources.

The 5 seconds was just for ‘demo’ purposes. It shows that this just works as planned. There is a caveat though:
The page gets rendered after the service method executed. This is what I was trying to prevent. Even before the method would execute, I wanted to send the headers out. So, this is kind of different from the early flush functionality, but it helps.

The banner jankiness is due to DFP (Google) serving different sizes. We are taking that out again, since it is disturbing, but thanks for reporting this. I will check out the link you provided.