0

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.

1

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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.