When replacing the body element via fetch, what is required to get the script to load?

I’m trying to learn PHP for authentication; and attempting to POST the username and password to a PHP script via fetch and, if successful, pass page content back to the client to replace the <body> element. It may be a stupid method; I don’t enough about it yet to know.

It works except the script in the body doesn’t load. I can see the script in the developer tools inspector but it isn’t working. The CSS file works.

Could you please tell me how to get the script to run? Thank you.

  "use strict";
  function postit() {
    var fd;
    try {
      fd = new FormData();
      fd.append("username", i[0].value);
      fd.append("passwd", i[1].value);

      fetch('login.php', {
        method: 'POST',
        body: fd
      })
      .then( response => {
        if ( !response.ok ) {
          throw new Error( 'Network response was not ok.' );
        } else {
          const contentType = response.headers.get('content-type');
          if (!contentType || !contentType.includes('text/html')) {
            throw new TypeError("Oops, we haven't got html.");
          }
        }
        return response.text();
      } )
      .then( data => {
         let p = new DOMParser(),
             b = p.parseFromString( data, 'text/html' );
        document.querySelector("head").appendChild( b.head.lastElementChild );
        document.body.parentNode.replaceChild( b.body, document.body );
      })
      .catch( error => {
        console.error('Error:', error);
      })
      .finally( () => {
      });
    } catch (err) {
      console.log( "Error in postit(); reason below.");
      console.log(err);
    } finally {
      fd = null;
    }
  }

  var i = document.querySelectorAll("input");