Click here to Skip to main content
15,892,059 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi everyone, I'm attempting to import an external script into an HTML file. The name of the js file that I want to import is hosted in a SQL database. Therefore, I am using a XMLHttpRequest to access the SQL database so that I can fetch the appropriate name of the script. I then create a script element where I set src equal to 'this.responseText' which should import the name taken from the SQL database. However, the script isn't being executed and I believe it's because it's run within a function. Therefore, I would like to append the js.src to the top of the header next to 'script1' and 'script2' which I assume would then allow the script to be imported successfully. Any ideas as to how this can be done?

HTML
<pre><head>

    <title>Columbia University HIT</title>
    <script src = "script1.js"></script>
    <script src = "script2.js"></script>


    <script>


    function reqListener () {
      console.log(this.responseText);
    }

    var oReq = new XMLHttpRequest(); // New request object
    oReq.onload = function() {
        const js = document.createElement("script");
        var noQuotes = this.responseText.split('"').join('');   //removes double quotes 
        js.src = noQuotes;   // script that I want to move to top of header next to 'script1' and 'script2'

    };


    console.log(oReq.onload.);
    oReq.open("get", "index.php", true);
    oReq.send();



    </script>



</head>



What I have tried:

I tried to append the script within the function but this didn't work.
var head = document.getElementsByTagName('head')[0];head.appendChild(js);
Posted
Comments
Richard Deeming 19-Jul-21 4:52am    
Check your browser's developer console for error messages. You're probably specifying the wrong path.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900