M
M
Maksim Tynkovich2021-12-12 16:31:56
JavaScript
Maksim Tynkovich, 2021-12-12 16:31:56

Problems with loading the site on React, how to fix it?

There is a site written in React, it is possible to change the theme from white to black with saving in LocalStorage, if you leave the black theme, then the white theme is visible for a split second when the page is loaded, how can I fix this? Please tell
me LocalStorage:

function switchMode() {
        if (document.documentElement.hasAttribute('data-theme')) {
            document.documentElement.removeAttribute('data-theme');
            localStorage.removeItem('data-theme');
        } else {
            document.documentElement.setAttribute('data-theme', 'dark');
            localStorage.setItem('data-theme', 'dark');
        }
    }

    window.onload = function () {
        if (localStorage.getItem('data-theme') === 'dark') {
            document.documentElement.setAttribute('data-theme', 'dark');
        }
    }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
Nikita Chernov, 2021-12-12
@wildfires

This script must be executed as early as possible: connect it as async in the header or even inline it.
This is required so that it executes before parsing and styles are completed.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question