Appending script from within function to header [closed]

Posted on

Problem

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?

<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>

Solution

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

document.body.appendChild(js):

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

let myScript = document.createElement("script");
myScript.setAttribute("src", "https://www.example.com/foo.js");
myScript.setAttribute("async", "false");
let head = document.head;
head.insertBefore(myScript, head.firstElementChild);

Reference :https://www.kirupa.com/html5/loading_script_files_dynamically.htm

Leave a Reply

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