Where is test
function called, is it synchronous so the script isn't fully loaded?
Maybe using an asynchronous call can avoid the problem:
const useScript = url => {
const script = document.createElement('script');
script.src = url;
script.async = true;
console.log("script");
document.body.appendChild(script);
};
return (
<div>
<button onClick={test}>Run Test</button>
<div id="myOutput"></div>
</div>
);