Showing a loading screen while initializing a Blazor application

 
 
  • Gérald Barré

Blazor applications often require initialization steps before they are ready to use. For example, you may need to fetch user data from a web API. Depending on network conditions, this can be nearly instant or take a few seconds, so showing a loading screen during initialization improves the user experience.

The answer to most things in Blazor is to create a component! In this case, the component loads data asynchronously and displays a loading message in the meantime. Once the data is loaded, it replaces the loading message with the actual content. If you wrap the main component (typically the Router) with this loading component, the user will see the loading message until the application is ready. If you have multiple initialization steps, you can even use a progress bar to indicate progress.

To create the component, create a new file named Shared/LoadingScreen.razor with the following content:

Razor
@if (isLoaded)
{
    @ChildContent
}
else
{
    <div>Loading screen...</div>
}

@code {
    bool isLoaded;

    [Parameter]
    public RenderFragment ChildContent { get; set; }

    protected override async Task OnInitializedAsync()
    {
        await Task.Delay(4000); // TODO actual initialization job
        isLoaded = true;
    }
}

The code is straightforward. The key detail is RenderFragment ChildContent { get; set; }. This parameter is a template whose value comes from the child content of the component, and you can render it using @ChildContent when needed. In this case, the content is displayed only after the component finishes its initialization.

You can then use the loading component in the App.razor file:

Razor
@* 👇 Wrap the Router in the LoadingScreen component *@
<LoadingScreen>
    <Router AppAssembly="@typeof(Program).Assembly">
        <Found Context="routeData">
            <RouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)" />
        </Found>
        <NotFound>
            <LayoutView Layout="@typeof(MainLayout)">
                <p>Sorry, there's nothing at this address.</p>
            </LayoutView>
        </NotFound>
    </Router>
</LoadingScreen>

If everything goes well, you should see something like the following when you start your application:

Note that this doesn't replace the default Blazor loading message. To replace this message, you can check my previous post about customizing the Blazor WebAssembly loading screen

Do you have a question or a suggestion about this post? Contact me!

Follow me:
Enjoy this blog?