mirror of
https://github.com/ChenQihan666/MyBlog-Next.git
synced 2026-08-14 07:33:07 +08:00
refactor: optimize theme script to prevent render-blocking (#601)
* refactor: optimize theme script to prevent render-blocking - Move theme script from `public/` to `src/scripts/` - Split into minimal inline script (FOUC prevention) + external script (non-blocking) - Rename `primaryColorScheme` to `initialColorScheme` - Rename `toggle-theme.js` to `theme.ts` - Use TypeScript for theme script - Update docs for theme customization
This commit is contained in:
@@ -130,10 +130,41 @@ const structuredData = {
|
||||
|
||||
<ClientRouter />
|
||||
|
||||
<script is:inline src="/toggle-theme.js"></script>
|
||||
<!-- Minimal inline script to prevent FOUC - sets theme immediately -->
|
||||
<script is:inline>
|
||||
(function () {
|
||||
const initialColorScheme = ""; // "light" | "dark"
|
||||
const currentTheme = localStorage.getItem("theme");
|
||||
|
||||
function getPreferTheme() {
|
||||
if (currentTheme) return currentTheme;
|
||||
if (initialColorScheme) return initialColorScheme;
|
||||
return window.matchMedia("(prefers-color-scheme: dark)").matches
|
||||
? "dark"
|
||||
: "light";
|
||||
}
|
||||
|
||||
const themeValue = getPreferTheme();
|
||||
|
||||
// Set theme immediately to prevent flash
|
||||
document.firstElementChild?.setAttribute("data-theme", themeValue);
|
||||
|
||||
// Export minimal API for external script
|
||||
window.theme = {
|
||||
themeValue: themeValue,
|
||||
getTheme: () => window.theme.themeValue,
|
||||
setTheme: val => {
|
||||
window.theme.themeValue = val;
|
||||
},
|
||||
};
|
||||
})();
|
||||
</script>
|
||||
</head>
|
||||
<body>
|
||||
<slot />
|
||||
|
||||
<!-- Load full theme logic -->
|
||||
<script src="../scripts/theme.ts"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
|
||||
Reference in New Issue
Block a user