Most of packages to do the job are outdated at the date. I found a solution that maybe can be useful for someone and it´s using a hook with the advantage you can control the state and take action based on it.
import { useEffect, useState } from 'react';
export const useExternalScript = (url) => {
let [state, setState] = useState(url ? "loading" : "idle");
useEffect(() => {
if (!url) {
setState("idle");
return;
}
let script = document.querySelector(`script[src="${url}"]`);
const handleScript = (e) => {
setState(e.type === "load" ? "ready" : "error");
};
if (!script) {
script = document.createElement("script");
script.type = "application/javascript";
script.src = url;
script.async = true;
document.body.appendChild(script);
script.addEventListener("load", handleScript);
script.addEventListener("error", handleScript);
}
script.addEventListener("load", handleScript);
script.addEventListener("error", handleScript);
return () => {
script.removeEventListener("load", handleScript);
script.removeEventListener("error", handleScript);
};
}, [url]);
return state;
};
Use it is simple as do:
const externalScript = 'https://player.live-video.net/1.6.1/amazon-ivs-player.min.js';
const scriptStatus = useExternalScript(externalScript);
useEffect(() => {
if (scriptStatus === 'ready') {
// Do something with it
}
}, [scriptStatus]);