2

While appending a script tag programmatically after the head element,

head.appendChild(script_elm);

within this above script element, i am defining a variable. If i want to access the variable which is defining within the script tag, it does not work immediately after the head append. Why?

Deepak Keynes
  • 2,291
  • 5
  • 27
  • 56
  • If you are loading an external JavaScript file you must wait it to be fully loaded before accessing to variables. – DanieleAlessandra Jan 03 '19 at 12:07
  • Possible duplicate of [Call javascript function after script is loaded](https://stackoverflow.com/questions/14644558/call-javascript-function-after-script-is-loaded) – Daut Jan 03 '19 at 12:23

2 Answers2

3

You need to wait for the script to be loaded. as @DanieleAlessandra comments

 script_elem.onload = function() {
      // some code
    };

see this question

Call javascript function after script is loaded

sferret
  • 361
  • 2
  • 14
  • Personally I would never "wait" for a single piece of script to load a single variable. I would suggest either using an `ajax` call to request the variable, or use a `serversided preprocessor` (like PHP) or simply include the script in the `head` and wait for the `DOMContentLoaded` event. – BRO_THOM Jan 03 '19 at 13:18
1

Be sure to make access to that variable available through your script. For example, external-script.js

window.externalScript = function () {

    const yourVariable = //do some magic here;
    this.scriptVariable = yourVariable;
    // your code
}

Then you can use this variable in your onload function like so:

script_elem.onload = () => {
    if (window.externalScript &&
        window.externalScript().scriptVariable) {
        //do whatever you want to do with your script variable.
    }
}
darth-coder
  • 670
  • 8
  • 20