如何修复 NextJS 中的深色模式背景颜色闪烁?

kyl*_*oki 4 javascript themes user-experience reactjs next.js

所以我的问题是 Next.js 无法在客户端访问localStorage,因此将发送默认情况下具有或不具有class="dark".

这意味着当用户重新加载页面时,在某些 javascript 执行并添加到之前,<html>短暂地没有class="dark",导致浅色背景颜色闪烁。如果我将 HTML 与 一起发送,则会出现同样的问题,但情况相反:那么浅色模式用户将在从 中删除之前体验到深色背景颜色的闪烁。class="dark"<html>class="dark"class="dark"<html>

有没有办法在页面渲染之前执行一些javascript?然后我就可以根据class="dark"用户<html>localStorage.

And*_*oss 5

当然,将noflash.js包含以下内容的文件添加到您的公共目录中

(function () {
    // Change these if you use something different in your hook.
    var storageKey = 'darkMode';
    var classNameDark = 'dark-mode';
    var classNameLight = 'light-mode';

    function setClassOnDocumentBody(darkMode) {
        document.body.classList.add(darkMode ? classNameDark : classNameLight);
        document.body.classList.remove(darkMode ? classNameLight : classNameDark);
    }

    var preferDarkQuery = '(prefers-color-scheme: dark)';
    var mql = window.matchMedia(preferDarkQuery);
    var supportsColorSchemeQuery = mql.media === preferDarkQuery;
    var localStorageTheme = null;
    try {
        localStorageTheme = localStorage.getItem(storageKey);
    } catch (err) {}
    var localStorageExists = localStorageTheme !== null;
    if (localStorageExists) {
        localStorageTheme = JSON.parse(localStorageTheme);
    }

    // Determine the source of truth
    if (localStorageExists) {
        // source of truth from localStorage
        setClassOnDocumentBody(localStorageTheme);
    } else if (supportsColorSchemeQuery) {
        // source of truth from system
        setClassOnDocumentBody(mql.matches);
        localStorage.setItem(storageKey, mql.matches);
    } else {
        // source of truth from document.body
        var isDarkMode = document.body.classList.contains(classNameDark);
        localStorage.setItem(storageKey, JSON.stringify(isDarkMode));
    }
})();

// https://github.com/donavon/use-dark-mode/blob/develop/noflash.js.txt
Run Code Online (Sandbox Code Playgroud)

然后,将以下标记添加到包含在文件类script src中的返回内容中Headpages/_document

import Document, {
    Head,
    Html,
    Main,
    NextScript,
    DocumentContext
} from 'next/document';

class MyDocument extends Document {
    static async getInitialProps(ctx: DocumentContext) {
        const initialProps = await Document.getInitialProps(ctx);
        return { ...initialProps };
    }
    render() {
        return (
            <Html lang='en-US'>
                <Head>
                    <meta charSet='utf-8' />
                    <script type="text/javascript" src='/noflash.js' />
                </Head>
                <body className='loading'>
                    <Main />
                    <NextScript />
                </body>
            </Html>
        );
    }
}

export default MyDocument;

Run Code Online (Sandbox Code Playgroud)

上述方法有效,但以下方法与 Nextv10+ 完美配合。它只需要将以下配置添加到根 next.config.js 文件中。

next.config.js

import Document, {
    Head,
    Html,
    Main,
    NextScript,
    DocumentContext
} from 'next/document';

class MyDocument extends Document {
    static async getInitialProps(ctx: DocumentContext) {
        const initialProps = await Document.getInitialProps(ctx);
        return { ...initialProps };
    }
    render() {
        return (
            <Html lang='en-US'>
                <Head>
                    <meta charSet='utf-8' />
                    <script type="text/javascript" src='/noflash.js' />
                </Head>
                <body className='loading'>
                    <Main />
                    <NextScript />
                </body>
            </Html>
        );
    }
}

export default MyDocument;

Run Code Online (Sandbox Code Playgroud)

pages/_document然后,如下所示更改文件中的以下脚本标记

before

module.exports = {
  env: {
    noflash: fs.readFileSync('/noflash.js').toString()
  }
}
Run Code Online (Sandbox Code Playgroud)

after

//
        <Head>
            <meta charSet='utf-8' />
            <script type="text/javascript" src='/noflash.js' />
        </Head>
//
Run Code Online (Sandbox Code Playgroud)

链接到我使用第一种方法的存储库(从 2020 年秋季开始,在 tailwindcss 内置深色模式支持之前)