From 9baa0c335b130a440c9af2f73bdf3ab77a04c6b3 Mon Sep 17 00:00:00 2001 From: iFwu Date: Tue, 8 Oct 2024 01:34:44 +0800 Subject: [PATCH] set interval to avoid block --- src/hooks/useOpenCV.ts | 13 ++++++++++--- vite.config.ts | 2 +- 2 files changed, 11 insertions(+), 4 deletions(-) diff --git a/src/hooks/useOpenCV.ts b/src/hooks/useOpenCV.ts index 0d100f4..6f4be39 100644 --- a/src/hooks/useOpenCV.ts +++ b/src/hooks/useOpenCV.ts @@ -23,21 +23,28 @@ export function useOpenCV() { } }; useEffect(() => { + let intervalId: number; const initialize = async () => { - if (typeof cv !== 'undefined') { + if (window.cv) { await new Promise((resolve) => { cv.onRuntimeInitialized = resolve; }); await onOpenCVReady(); } else { - document.addEventListener('opencv-loaded', onOpenCVReady); + window.addEventListener('opencv-loaded', onOpenCVReady); + intervalId = setInterval(() => { + if (!isLoading) { + onOpenCVReady(); + } + }, 500); } } initialize(); return () => { - document.removeEventListener('opencv-loaded', onOpenCVReady); + window.removeEventListener('opencv-loaded', onOpenCVReady); + clearInterval(intervalId); }; }, []); diff --git a/vite.config.ts b/vite.config.ts index a5b243f..d782237 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -28,7 +28,7 @@ export default defineConfig({ injectTo: 'body', attrs: { async: true, - onload: 'cv.onRuntimeInitialized = () => { document.dispatchEvent(new Event(\'opencv-loaded\')); }', + onload: 'cv.onRuntimeInitialized = () => { window.dispatchEvent(new Event(\'opencv-loaded\')); }', }, }; },