mirror of
https://github.com/jakejarvis/jarv.is.git
synced 2025-07-21 05:41:17 -04:00
more optimization/error handling
This commit is contained in:
@@ -1,32 +1,34 @@
|
||||
import { memo } from "react";
|
||||
import { useMemo } from "react";
|
||||
import { minify } from "uglify-js";
|
||||
import { clientScript } from "./script";
|
||||
import { darkModeQuery, themeStorageKey, themeClassNames } from "../../lib/config/themes";
|
||||
|
||||
const ThemeScript = () => {
|
||||
// since the function above will end up being injected as a plain dumb string, we need to set the dynamic values here:
|
||||
const functionString = String(clientScript)
|
||||
.replace('"__MEDIA_QUERY__"', `"${darkModeQuery}"`)
|
||||
.replace('"__STORAGE_KEY__"', `"${themeStorageKey}"`)
|
||||
.replace('"__CLASS_NAMES__"', JSON.stringify(themeClassNames))
|
||||
.replace(
|
||||
'"__LIST_OF_CLASSES__"',
|
||||
Object.values(themeClassNames)
|
||||
.map((t: string) => `"${t}"`)
|
||||
.join(",")
|
||||
);
|
||||
const minified = useMemo(() => {
|
||||
// since the client function will end up being injected as a plain dumb string, we need to set dynamic values here:
|
||||
const functionString = String(clientScript)
|
||||
.replace('"__MEDIA_QUERY__"', `"${darkModeQuery}"`)
|
||||
.replace('"__STORAGE_KEY__"', `"${themeStorageKey}"`)
|
||||
.replace('"__CLASS_NAMES__"', JSON.stringify(themeClassNames))
|
||||
.replace(
|
||||
'"__LIST_OF_CLASSES__"',
|
||||
Object.values(themeClassNames)
|
||||
.map((t) => `"${t}"`)
|
||||
.join(",")
|
||||
);
|
||||
|
||||
// minify the final code, a bit hacky but this is ONLY done at build-time, so uglify-js is never bundled or sent to
|
||||
// the browser to execute:
|
||||
const minified = minify(`(${functionString})()`, {
|
||||
toplevel: true,
|
||||
compress: {
|
||||
negate_iife: false,
|
||||
},
|
||||
parse: {
|
||||
bare_returns: true,
|
||||
},
|
||||
}).code;
|
||||
// minify the final code, a bit hacky but this is ONLY done at build-time, so uglify-js is never bundled or sent to
|
||||
// the browser to execute:
|
||||
return minify(`(${functionString})()`, {
|
||||
toplevel: true,
|
||||
compress: {
|
||||
negate_iife: false,
|
||||
},
|
||||
parse: {
|
||||
bare_returns: true,
|
||||
},
|
||||
}).code;
|
||||
}, []);
|
||||
|
||||
// the script tag injected manually into `<head>` in _document.tsx.
|
||||
// even though it's the proper method, using next/script with `strategy="beforeInteractive"` still causes flash of
|
||||
@@ -36,10 +38,10 @@ const ThemeScript = () => {
|
||||
key="restore-theme"
|
||||
dangerouslySetInnerHTML={{
|
||||
// make it an IIFE:
|
||||
__html: `(function(){${minified}})();`,
|
||||
__html: `(function(){${minified}})()`,
|
||||
}}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
export default memo(ThemeScript);
|
||||
export default ThemeScript;
|
||||
|
Reference in New Issue
Block a user