Created
July 30, 2022 04:59
-
-
Save leifarriens/5a6ee3616f3fa30faa1e02473e0e463b to your computer and use it in GitHub Desktop.
React Hook to load script
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function useScript(id, src, options = {}) { | |
const { persist = true, onLoad } = options; | |
const [ready, setReady] = useState(false); | |
useEffect(() => { | |
const domScript = document.getElementById(id); | |
if (!domScript) { | |
const script = document.createElement('script'); | |
script.src = src; | |
script.id = id; | |
document.body.appendChild(script); | |
script.onload = () => { | |
setReady(true); | |
onLoad && onLoad(); | |
}; | |
} | |
setReady(true); | |
return () => { | |
if (!persist) { | |
const domScript = document.getElementById(id); | |
document.body.removeChild(domScript); | |
} | |
}; | |
}, [id, src, persist, onLoad]); | |
return { ready }; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment