Appending script from within function to header [closed]

Posted on


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?


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


function reqListener () {

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.);"get", "index.php", true);



I think the way you have created the element is correct but it needs to to be added to DOM.
Add the script element to the DOM using


If you want it to be added at top try doing something like this

let myScript = document.createElement("script");
myScript.setAttribute("src", "");
myScript.setAttribute("async", "false");
let head = document.head;
head.insertBefore(myScript, head.firstElementChild);

Reference :

Leave a Reply

Your email address will not be published. Required fields are marked *