첫 커밋
This commit is contained in:
37
src/shared/lib/hooks/use-script.ts
Normal file
37
src/shared/lib/hooks/use-script.ts
Normal file
@@ -0,0 +1,37 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
|
||||
export function useScript(src: string) {
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState(null);
|
||||
|
||||
useEffect(() => {
|
||||
let script = document.querySelector(`script[src="${src}"]`);
|
||||
|
||||
const handleLoad = () => setLoading(false);
|
||||
const handleError = (err: any) => {
|
||||
setError(err);
|
||||
setLoading(false);
|
||||
};
|
||||
if(!script){
|
||||
script = document.createElement('script');
|
||||
(script as any).src = src;
|
||||
(script as any).type = 'text/javascript';
|
||||
(script as any).charset = 'utf-8';
|
||||
|
||||
script.addEventListener('load', handleLoad);
|
||||
script.addEventListener('error', handleError);
|
||||
console.log(script);
|
||||
// document.getElementsByTagName('head')[0].appendChild(script);
|
||||
}
|
||||
else{
|
||||
setLoading(false);
|
||||
}
|
||||
|
||||
return () => {
|
||||
script.removeEventListener('load', handleLoad);
|
||||
script.removeEventListener('error', handleError);
|
||||
}
|
||||
}, [src]);
|
||||
|
||||
return [loading, error];
|
||||
}
|
||||
Reference in New Issue
Block a user