Reputation: 57
I am trying to calling a variable defined in another file. I have the following code in my HTML
file surrounded by <script>
tags within the body.
function getScript("./analysis_method.js", callback) {
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = "./analysis_method.js";
script.onreadystatechange = callback;
script.onload = callback;
document.getElementsByTagName('head')[0].appendChild(script);
}
getScript('./analysis_method.js', function() {
alert("Analysis Method: " + method);
});
In analysis_method.js
I have defined method
like this: var method = "thermometer";
I got this code off of another Stack Overflow question and I changed what I understood for my project. I believe my issue is that I have not changed callback
although I don't know what to change it to.
Upvotes: 0
Views: 595
Reputation: 18780
You have a syntax error in your getScript definition.
function getScript(url, callback) {
...
script.src = url;
...
}
It is important to understand that you cannot use string or number literals as variable names and that all function arguments must be defined with variable names.\
You should also likely expect that the callbacks for onreadystatechange
will fail until the script is actually loaded. onreadystatechange
is generally used to hold a callback that checks for success or failure and invokes the appropriate callback when one of those conditions is met.
Upvotes: 3