Showing a loading screen while initializing a Blazor application

  • Gérald Barré

Your Blazor application may require some initialization steps. For instance, you may need to get the user data from a web API before the user can use the application. Depending on the network this can be fast or take a few seconds. You may want to show a loading screen while initializing the application.

The solution to everything in Blazor is to create a component! In this case, the component will load the data asynchronously and display a loading message meanwhile. Once the data is loaded, it replaces the loading message with the actual content. So, if you wrap the main component (surely the Router) by 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 the progression.

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

@if (isLoaded)
    <div>Loading screen...</div>

@code {
    bool isLoaded;

    public RenderFragment ChildContent { get; set; }

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

The code is pretty simple. The only trick is to use RenderFragment ChildContent { get; set; }. This parameter is a template that takes its value from the child content of the component and you can render it using @ChildContent when needed. In this case, we display the content only when the component has finished its initialization.

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

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

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?Buy Me A Coffee💖 Sponsor on GitHub