如何消除深色模式重新加載期間的白色背景閃爍
在應(yīng)用中實(shí)現(xiàn)深色模式時,解決白色問題至關(guān)重要頁面重新加載時背景閃爍。這種難看的閃爍是在頁面最初以淺色模式加載然后切換到深色模式之前發(fā)生的。
解決方案:阻止頁面渲染
解決此閃爍問題的關(guān)鍵在于阻塞頁面渲染。通過在
中放置一個小腳本標(biāo)簽文檔部分,您可以停止 DOM 解析器進(jìn)程。這允許 JavaScript 解釋器將 data-theme 屬性分配給 。實(shí)現(xiàn):
- 將腳本添加到 添加腳本到
<code class="html"><script> // Set the theme in <HEAD> before any other tag. const setTheme = (theme) => { theme ??= localStorage.theme || "light"; document.documentElement.dataset.theme = theme; localStorage.theme = theme; }; setTheme(); </script></code>
- 將腳本移動到 的末尾:
<code class="html"><script src="js/index.js"></script> <!-- Other <script> tags here --> </body> </html></code>以非渲染阻塞方式將所有其他腳本放置在之前結(jié)束語