Franck
Franck

Reputation: 1

Dark/Light theme rendering issue Blazor .NET8

I'm trying to add a class 'dark' if it is in localstorage, and remove it if there is 'light' as 'mode' in localstorage. However, I have the feeling that all pages of my blazor .NET8 application are cached. It saves the mode in local storage, but when I switch pages it doesn't execute the javascript 'onload' statement. Only if I then manually refresh the page again.

I'm curious, does Blazor cache all the pages, because it doesn't re-render the page when you go to it. Does this have to do with a specific rendermode in Blazor?

What I've tried is using the 'onload' param in the body tag. However the onload statement is'nt executed when rendering the page.

<body onload="localStorage.getItem('mode') === 'dark' ? document.querySelector('body').classList.add('dark') : document.querySelector('body').classList.remove('dark')">

I've tried using OnAfterRednerAsync but it applies the styling after it's being rendered. The result you'll get is that the screen show lightmode for a quick millisecond and then applies the 'dark' class to the body tag.

Upvotes: 0

Views: 89

Answers (1)

Josh
Josh

Reputation: 161

Id make use of IJSRuntime in blazor and then make a call from when home page component or similar is rendered:

 protected override async Task OnAfterRenderAsync(bool firstRender) {
 if (firstRender)
 {
     await JSRuntime.InvokeVoidAsync("jsmethodToExecute");
 }
 }

find more here: JSRuntime

Upvotes: 0

Related Questions