I have a project in which I am using a CDN to load a script. I load it via useEffect
in my component directly. Simplified code:
React.useEffect(() => {
const script = document.createElement('script');
script.src = "https://cdn.cubing.net/js/cubing/twisty";
script.type= "module";
document.body.appendChild(script);
return () => {
document.body.removeChild(script);
}
}, []);
return (
<twisty-player>
</twisty-player>
)
Twisty-player is the custom HTML tag that comes from the script (it is not a react component). The documentation for it is here: https://js.cubing.net/cubing/twisty/
I have a few questions:
- This code works for me, but I don't understand why, because we aren't awaiting anything. I render the
twisty-player
right after we load the script, but we aren't waiting for the script to finish downloading, so I'm not sure how we are able to render it. - Is this the recommended way to add the script for the
twisty-player
? Is there a better way to do it? - I tried to load the script directly into the HTML head, and then I removed my entire
useEffect
statement from my component, but this did not work, why is that?