I have the following code:
Hook:
import { useEffect } from 'react';
const useScript = url => {
useEffect(() => {
const script = document.createElement('script');
script.src = url;
script.async = true;
document.body.appendChild(script);
return () => {
document.body.removeChild(script);
}
}, [url]);
};
export default useScript;
Use:
useScript("script1.js")
useScript("script2.js")
useScript("script3.js")
How I would like to use it:
useScriptMulti("script1.js","script2.js","script3.js")
Can you give me a hand?
scriptelement from the DOM doesn't do anything to the code it loaded. Once you've loaded a script, you can't unload it (in the general case; it's possible to write a script that can fully clean itself up). 2. There's no reason to useasync = trueon ascriptelement you're adding dynamically after the main HTML parsing is complete, it has no effect.asyncthing I'm missing, though frankly I don't think so. Note that they don't remove the script element in the cleanup (presumably because there's no point).