Showing a loading screen while initializing a Blazor application
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)
{
@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 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 *@
<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!