JS file not executed when coming back to a page in SPA

I’m building an SPA where the router function calls the server and receives JSON response like

{
   "content": ...,
   "css": ...,
   "js": ...
}

and puts everything in the right place while also removing the old content. The problem is with js files (not inline scripts). On first load of the page, they get executed just fine. Then I navigate to page 2, the js of page 1 are removed. I then press the back button, which does trigger the router function and loads the content of page 1 along with js files. The script tags are created but the js never executes. Here’s the code for creating the script tags.

   function loadScript(url, type = null){
        const script = document.createElement('script');
        script.src = url;
        if(type != null)
            script.type = type;
        script.classList.add('page-js');
        document.body.appendChild(script);

        return new Promise((res, rej) => {
          script.onload = () => {
            console.log(script, 'script loaded'); // executes everytime
            res();
          };
          script.onerror = rej;
        });
   }

I tried wrapping my code in a SIAF but that didn’t make a difference. If I make the url unique like this, then the code executes.

script.src = url+'?v='+Math.random();

So most likely its a caching problem but if I do a page refresh (not handled by router), the code executes again without v parameter. What is the appropriate way of handling this in an SPA?