AndroidKid
AndroidKid

Reputation: 199

How to run functions from a dynamically loaded script

I am trying to load a js script dynamically in index.html file using appendChild DOM method. And I am trying to use some functions from that dynamically loaded js in next line itself but I am getting error that the specified function is undefined. I understand that this error is because of async behavior of loading scripts in browser. I also used async flag as false but no use. Below are sample code.

<script> 
var head = document.getElementsByTagName('head')[0];
var js = document.createElement("script");
js.type = "text/javascript";
js.async = false;
js.src = "https://example.com/test.js"; // There are two variants of test.js is there. Will be changing it dynamically based on conditional check.
head.appendChild(js);
</script>
<script> 
   test(); // Method inside test.js
</script>

I want test.js to be loaded immediately after executing appendChild code part. Please help me on this. Please suggest if there is any other way for my purpose.

Upvotes: 0

Views: 1369

Answers (1)

user5734311
user5734311

Reputation:

Synchronized XHRs are deprecated. You need to add an event listener so you can call your code as soon as the script is loaded. Example below:

var head = document.getElementsByTagName('head')[0];
var js = document.createElement("script");
head.appendChild(js);
js.onload = function() {
  console.log("yes", window.$)
};
js.src = "//code.jquery.com/jquery-3.3.1.min.js";
console.log("nope", window.$)

Upvotes: 2

Related Questions