How to properly append a script dynamically using vanilla javascript? [duplicate]

I’m trying to make an SPA with dynamic content in vanilla js and made these functions below. ${script.src} shows the correct js file but the code inside it doesn’t take effect. I had another console.log inside the js file which didn’t show in the console. I am now confused why this code adds the correct script line in the html but the code inside the js file/script doesn’t take effect. I tried the js file in a separate static html and it works. So the code isn’t the issue but how the script is appended. Can anybody tell me what I’m missing?

const renderContent = (route) => {
    fetch("site/pages" + route + ".html")
        .then(response => response.text())
        .then(html => {
            app.innerHTML = html;
            loadScript(route, app);
        })
        .catch(error => console.error("Error loading HTML:", error));
};
const loadScript = (page, app) => {
    const script = document.createElement('script');
    script.src = 'site/js' + page + '.js';
    script.type = 'text/javascript';
    script.defer = true;
    script.onload = () => {
        console.log(`Script loaded and executed: ${script.src}`);
    };
    script.onerror = () => {
        console.error(`Failed to load script: ${script.src}`);
    };

    app.appendChild(script);
};