BlazorStrap icon indicating copy to clipboard operation
BlazorStrap copied to clipboard

SetBootstrapCss updates after page renders

Open scubakiz opened this issue 3 years ago • 4 comments

By setting this in the MainLayout, the theme is updated after the page is rendered. So for a half second, the user sees unformatted content, including the top menu before the theme is applied.

image

Is there any way around this?

scubakiz avatar Apr 11 '21 04:04 scubakiz

You have two options.

  1. Call the function as soon as allowed. For example our demo page is this.
    private bool isServerSide = false; 
    protected override async Task OnInitializedAsync()
    {
        try
        {
            await BootstrapCSS.SetBootstrapCSS("4.5.0");
        }
        catch (Exception)
        {
            //Javascript was not ready so fails we handle it on after the first render
            isServerSide = true;
        }
    }

    protected override async Task OnAfterRenderAsync(bool firstrun)
    {
        // Only run if the task failed in on init
        if (isServerSide && firstrun)
        {
            await BootstrapCSS.SetBootstrapCSS("4.5.0");
        }
    }
  1. If your using a static version of bootstrap and it does not change in your site include the bootstrap style sheet inside your index.html/index.cshtml and do not use SetBootstrapCSS at all.

jbomhold3 avatar Apr 11 '21 09:04 jbomhold3

Well option number 3 show a loading screen until after first render then hide it. Since at this point blazor is now completely ready for everything.

@if(Ready) { @Body; } else { Your loading screen or message } code {

    private bool Ready= false; 
    protected override async Task OnAfterRenderAsync(bool firstrun)
    {
        // Only run if the task failed in on init
        if (firstrun)
        {
            await BootstrapCSS.SetBootstrapCSS("4.5.0");
            Ready = true;
            await InvokeAsync(StateHasChange);
        }
    }

}

jbomhold3 avatar Apr 11 '21 10:04 jbomhold3

Option 1 doesn't actually work. I'm using server-side rendering and I still see a flash of unstyled content on first load.

doxxx avatar Mar 16 '22 23:03 doxxx

Your always going to see a flash with server side prerendering. The method is a JavaScript call to add the link tag into the doms head area. Since this requires a client your it cannot be prerendered. Your best bet is to just use static includes for bootstrap if your counting on the newer prerendering then live capabilities added in new versions of Blazor.

jbomhold3 avatar Mar 17 '22 00:03 jbomhold3