420skun
420skun

Reputation: 139

How to prevent the flashing of content in a prerendered Blazor WebAssembly app?

The following code snippet can illustrate the issue present in Blazor applications which are rendered on the server side:

App.Client/Pages/Test.razor

@page "/test" 

<p>@text</p>

@code 
{
    private string text;

    protected override async Task OnInitializedAsync()
    {
        await Task.Delay(1000); // wait 1000 milliseconds
        text = "foo";
    }
}

When the component is first initailized on the server, the text variable is set to foo and a HTML document containing the string is sent over to the client. However, the client Blazor app isn't aware of the value that the server has assigned to the variable, which becomes null again. OnInitializedAsync is called again on the client and text is set back to foo, but only after a one second period during which there's nothing on the screen - a situation server-side rendering aims to avoid in the first place.

Do you know of any way to send components already populated with data?

Upvotes: 6

Views: 3147

Answers (1)

user14198340
user14198340

Reputation: 189

Ok -- just being a bit picky -- this is a Blazor page....it isn't a component.

Yes, the pre-render they use isn't great, but assuming you're using Blazor for a SPA it should only happen once. Be careful to avoid a hard reload if you use the Microsoft.AspNetCore.Components.NavigationManager NavigateTo method. A hard re-load triggers pre-rendering because you refresh the SPA.

To avoid the whiplash, you want to avoid needing 1 second to load the text value. So you could use a singleton controller and inject it into the page. On the pre-render pass the value isn't yet known so we need 1 second to load it. Then on the client side pass the data could be accessed via the controller immediately.

Granted this isn't perfect if there is a ton of data to display. But in cases like that I generally show a 'loading' spinner and it gives the customer a feeling of controlled motion.

Upvotes: 0

Related Questions