Skip to content

Commit

Permalink
feat: Add preloader for web workers
Browse files Browse the repository at this point in the history
  • Loading branch information
NriotHrreion committed Jun 6, 2024
1 parent 7353d3e commit 4d1ecb5
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 1 deletion.
7 changes: 6 additions & 1 deletion src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@ import { AliveScope } from "react-activation";
import { shortcuts } from "@/global";
import { Mode, RenderedFunction } from "@/types";
import Utils from "@/utils/Utils";
import { Axis } from "./renderer/Graphics";
import { Axis } from "@/renderer/Graphics";

import usePreloader from "@/hooks/usePreloader";

// Layout
import "katex/dist/katex.min.css";
Expand All @@ -28,6 +30,9 @@ const App: React.FC = () => {
const [functionList, setFunctionList] = useState<RenderedFunction[]>([]);
const [axis, setAxisType] = useState<Axis>(Axis.CARTESIAN);

usePreloader(new URL("@/workers/graphing.worker.ts", import.meta.url), "script");
usePreloader(new URL("@/workers/calculating.worker.ts", import.meta.url), "script");

useEffect(() => {
document.body.addEventListener("keydown", (e: KeyboardEvent) => {
shortcuts.forEach((shortcut, key) => {
Expand Down
16 changes: 16 additions & 0 deletions src/hooks/usePreloader.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
/* eslint-disable react-hooks/exhaustive-deps */
import { useEffect } from "react";

type PreloadType = "fetch" | "font" | "image" | "script" | "style" | "track";

export default function usePreloader(target: string | URL, as: PreloadType = "image") {
useEffect(() => {
var preloadElem = document.createElement("link");
preloadElem.rel = "preload";
typeof target === "string"
? preloadElem.href = target
: preloadElem.href = target.href;
preloadElem.as = as;
document.head.appendChild(preloadElem);
}, []);
}

1 comment on commit 4d1ecb5

@github-actions
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.