(Blazor - LayoutComponentBase) Detecting @Body lifecycle completion for loading page in layout

Viewed 185

So I am setting up a custom layout in Blazor effectively acting like the master page for the site. One of the bits of functionality was some async initialization that ran some of the more demanding and time consuming methods for that page. During this loading, the page contents would be hidden and a loading bar would flash. Once the processing was complete, a boolean would flip, thus showing the content.

I plan to move all of this code off of the individual pages, and onto the layout instead. The layout is used across many of the websites, so this would also introduce the functionality to other websites which did not have it before. It also keeps the functionality centralized in one place rather than duplicated across the pages using the layout.

So, the code:

Layout.Razor

@if (IsInitialised) { 
    <header><nav>...</nav></header>

    <main>@Body</main>

    <footer>...</footer>
} else { <LoadingOverlay OnShow="true" /> }

Layout.cs Class

protected override Task OnInitializedAsync() {
    return Task.Run(() => {
        Thread.Sleep(5000); //Represents a long process for a page launch.
        IsInitialised = true;
    });
}

The idea is to detect when the @Body has completed its lifecycle and then to set the IsInitilised to true.

The issue I am having is trying to get from the Body fragment when it has completed all of its tasks and the page is ready.

This was simple before, as on the pages specifically, I had access to the methods which would block the page from loading and just have the initialisation set once they were complete. However, now, I do not have these page specific methods for the generic functionality now desired out of the site's layout.

The desired outcome is something akin to:

protected override Task OnInitializedAsync() {
    return Task.Run(() => {
        Body.LifecylcleCompleted();
        IsInitialised = true;
    });
}

All ideas are appreciated, and of course, thank you for your time.

PS: Some issues I am already aware of with this structure are that OnInitializedAsync only runs once and isn't seemingly suitable for changing pages and having the loading bar work. Also, I plan to try and only wrap the @Body inside the if check also so the header and footer which are generally static across all pages remain with the loading animation happening between them. I planned to get all working first before attempting these modifications.

0 Answers
Related