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,3597 gold badges31 silver badges61 bronze badges
asked Jan 3, 2019 at 12:03
2
  • If you are loading an external JavaScript file you must wait it to be fully loaded before accessing to variables. Commented Jan 3, 2019 at 12:07
  • Possible duplicate of Call javascript function after script is loaded Commented Jan 3, 2019 at 12:23

2 Answers 2

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

answered Jan 3, 2019 at 12:14
Sign up to request clarification or add additional context in comments.

1 Comment

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.
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.
 }
}
answered Jan 3, 2019 at 13:14

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.