I am working on a React based PWA. For using an external service I have to add a JS script at runtime. Currently I'm adding it (based on the instructions provided by the service) to the document like so:
function initializeScript() {
const script = document.createElement('script');
script.id = 'source-script';
script.src = 'https://some.url.com';
document.body.appendChild(script);
}
Adding the script is successful as there is the following code available in the browser.
if (document.querySelector('#dom-source')) {
console.info("Binding to the window.onload event");
window.onload = function() {
console.info("The parent window is loaded");
// some code
};
}
The first console.info is being executed. However - and this is my main issue - the window.onload function isn't being executed after that. I guess that's due to the fact that I'm using React and it somehow never triggers the onload event.
Is there a workaround or am I missing something? I can't alter the source code of the added JS code as it's from an external provider. Also I have to add it dynamically after some initialization work of the #dom-source
element.
Any help would be much appreciated! Thanks!
UPDATE:
After some trial and error and based on this How do i use external script that i add to react JS? answer I came up with the following semi-working solution:
let A: any;
const scriptLoaded = useCallback(() => {
console.info('script loaded');
// @ts-ignore
A = new A() // A is a class in the external JS file
A.someFunctionOfScript();
}, [])
useEffect(() => {
const script = document.createElement('script');
script.id = 'source-script';
script.src = 'some.url.com'
script.onload = () => scriptLoaded();
document.body.appendChild(script);
return () => {
document.body.removeChild(script);
};
}, [token]);
Instead of waiting for the window.onload event, I'm executing the scriptLoaded function. Its code is just pasted from the external files window.onload function.
So this works perfectly up until unmounting or route switching. I'm getting exceptions from the external file. It basically tries to execute the code but the elements like #dom-source
are no longer available. Well, at least the script is being executed now.
Anyone got an idea of how to stop the script execution and remove all references to it when unmounting?