Skip to content

Commit

Permalink
refactor: improve useScripts hook for better loading efficiency (#408)
Browse files Browse the repository at this point in the history
  • Loading branch information
DimaDemchenko authored Aug 14, 2024
1 parent d090eb0 commit a54b552
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 26 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -19,31 +19,14 @@ export const HlsjsClapprPlayer = ({
onChunkDownloaded,
onChunkUploaded,
}: PlayerProps) => {
useScripts(SCRIPTS);
const areScriptsLoaded = useScripts(SCRIPTS);

const [isClapprLoaded, setIsClapprLoaded] = useState(false);
const [isHlsSupported, setIsHlsSupported] = useState(true);

const containerRef = useRef<HTMLDivElement>(null);

useEffect(() => {
let intervalId: NodeJS.Timeout | null = null;

const checkClapprLoaded = () => {
if (!window.Clappr && !window.LevelSelector) return;
if (intervalId) clearInterval(intervalId);
setIsClapprLoaded(true);
};

intervalId = setInterval(checkClapprLoaded, 200);

return () => {
if (intervalId) clearInterval(intervalId);
};
}, []);

useEffect(() => {
if (!containerRef.current || !isClapprLoaded) return;
if (!containerRef.current || !areScriptsLoaded) return;
if (!Hls.isSupported()) {
setIsHlsSupported(false);
return;
Expand Down Expand Up @@ -89,7 +72,7 @@ export const HlsjsClapprPlayer = ({
};
/* eslint-enable */
}, [
isClapprLoaded,
areScriptsLoaded,
announceTrackers,
onChunkDownloaded,
onChunkUploaded,
Expand Down
22 changes: 16 additions & 6 deletions packages/p2p-media-loader-demo/src/hooks/useScripts.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useEffect } from "react";
import { useEffect, useState } from "react";

const generateUniqueId = () => {
return `script-${Math.random().toString(36).substring(2, 11)}`;
Expand All @@ -22,6 +22,8 @@ const loadScript = (script: { url: string; id: string }) => {
};

export const useScripts = (scripts: string[]) => {
const [areScriptsLoaded, setAreScriptsLoaded] = useState(false);

useEffect(() => {
let isCleanup = false;

Expand All @@ -41,17 +43,25 @@ export const useScripts = (scripts: string[]) => {
};

const loadAllScripts = async () => {
for (const script of scriptsWithIds) {
await loadScript(script);
if (isCleanup) {
cleanUp();
break;
try {
for (const script of scriptsWithIds) {
await loadScript(script);
if (isCleanup) {
cleanUp();
break;
}
}
if (!isCleanup) setAreScriptsLoaded(true);
} catch (error) {
// eslint-disable-next-line no-console
console.error("Error loading scripts", error);
}
};

void loadAllScripts();

return () => cleanUp();
}, [scripts]);

return areScriptsLoaded;
};

0 comments on commit a54b552

Please sign in to comment.