I am converting a .net site to next.js. I don’t want to rewrite all the javascript so I am just loading their main.js file in the head of the layout file using a the next.js Script component. This file is 52,000 lines long and I don’t have the time to rewrite it all in React. Everything works well on load, but the javaScript doesn’t work after internal navigation, it only works when the page refreshes.
I’ve tried to remove the script tag and to reappend it when the path changes, however it only partially works. I assume some of the elements are not available in the DOM yet for events to be attached. There is a timing issue in that I need to wait for all the components to mount before appending this script, but there are 100’s of possible components.
useEffect(() => {
const script = document.createElement('sc`your text`ript');
script.src = '/Casino/assets/js/main.js';
script.async = true;
return () => {
document.body.removeChild(script);
};
}, [router.asPath]);
Is there a way to know when all elements have finished mounting? Is there another approach I can take with this?
Chris VanGroll is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.