Skip to content

Commit 43a65bf

Browse files
committed
Set meta theme color based on current theme on load to avoid flicker
1 parent a5911cf commit 43a65bf

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

src/pages/_document.tsx

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,34 @@
11
import InitColorSchemeScript from '@mui/material/InitColorSchemeScript';
22
import { Html, Head, Main, NextScript } from 'next/document';
33

4+
function InitMetaThemeColorScript(): React.ReactElement {
5+
return (
6+
<script
7+
dangerouslySetInnerHTML={{
8+
__html: `
9+
(function() {
10+
try {
11+
const currentTheme = document.documentElement.getAttribute('data-theme');
12+
13+
const matchingMetaTag = document.querySelector(
14+
\`meta[name="theme-color"][media*="\${currentTheme}"]\`
15+
);
16+
if (!matchingMetaTag) return;
17+
18+
const metaContentColor = matchingMetaTag.getAttribute('content');
19+
if (!metaContentColor) return;
20+
21+
document.querySelectorAll('meta[name="theme-color"]').forEach((meta) => {
22+
meta.setAttribute('content', metaContentColor);
23+
});
24+
} catch (_) {}
25+
})();
26+
`,
27+
}}
28+
/>
29+
);
30+
}
31+
432
export default function Document() {
533
return (
634
<Html lang="fi">
@@ -33,6 +61,7 @@ export default function Document() {
3361
</Head>
3462
<body>
3563
<InitColorSchemeScript attribute="data-theme" />
64+
<InitMetaThemeColorScript />
3665
<Main />
3766
<NextScript />
3867
</body>

0 commit comments

Comments
 (0)