diff --git a/src/hooks/useScript.js b/src/hooks/useScript.js index e39631f8a..b8de4b3b6 100644 --- a/src/hooks/useScript.js +++ b/src/hooks/useScript.js @@ -1,21 +1,33 @@ import { useEffect, useState } from 'react'; +import useShallowMemo from './useShallowMemo'; -const useScript = (src) => { +const useScript = (src, options) => { + const { attributes = {}, async: isAsync = true, crossOrigin } = options || {}; const [loaded, setLoaded] = useState(false); + const [error, setError] = useState(null); + const attrs = useShallowMemo(() => attributes, [attributes]); useEffect(() => { const script = window.document.createElement('script'); - script.async = true; - script.crossOrigin = 'anonymous'; - script.onload = () => setLoaded(true); + script.async = isAsync; + script.crossOrigin = crossOrigin; + script.onload = () => { + setLoaded(true); + }; + script.onerror = setError; script.src = src; + + Object.entries(attrs).forEach(([attribute, value]) => + script.setAttribute(attribute, value) + ); + document.body.appendChild(script); return () => document.body.removeChild(script); - }, [src]); + }, [src, attrs, isAsync, crossOrigin]); - return loaded; + return [loaded, { error }]; }; export default useScript;