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
-
If you are loading an external JavaScript file you must wait it to be fully loaded before accessing to variables.DanieleAlessandra– DanieleAlessandra2019年01月03日 12:07:52 +00:00Commented Jan 3, 2019 at 12:07
-
Possible duplicate of Call javascript function after script is loadedDaut– Daut2019年01月03日 12:23:58 +00:00Commented Jan 3, 2019 at 12:23
2 Answers 2
You need to wait for the script to be loaded. as @DanieleAlessandra comments
script_elem.onload = function() {
// some code
};
see this question
Sign up to request clarification or add additional context in comments.
1 Comment
BRO_THOM
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.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
darth-coder
81210 silver badges20 bronze badges
Comments
default