1

I want to use within a js file a variable that belongs to another js file. ie I want to run file1.js using a file2.js variable.

Does anyone know how to do this?
is it possible to access a variable from another .js file?

file1.js:

oScript = document.createElement('script');
oScript.src = 'file2.js';
oScript.type = 'text/javascript';
document.body.appendChild(oScript);
console.log(message);

file2.js:

var message = [{"id":"01", "name":"Text A", "text":"more text"},{"id":"02", "name":"Text B", "text":"more text"}];
3
  • are you calling these files with a script tag? Commented Dec 31, 2017 at 19:51
  • This code should work fine. message looks like a global variable, so it should be readable after your insert the script tag. What issue are you having? Commented Dec 31, 2017 at 19:51
  • You could create global variable that can be accessed by window.variableName Commented Dec 31, 2017 at 20:05

2 Answers 2

1

You need to ensure console.log(message) isn't run until after file2 is loaded. I suggest using AJAX instead of trying to inject the file into your HTML.

var xhr = new XMLHttpRequest();
xhr.open('GET', 'file2.js');
xhr.onload = function() {
    eval(xhr.responseText);
    console.log(message);
    window.message = message; //Include this if you need message to be a global variable
};
xhr.send();

However, I highly recommend using a JSON file to store the value of the message variable and loading that with ajax, rather than using JavaScript code.

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

Comments

0

You can do this with just a script tag if you use the load event:

oScript = document.createElement('script');
oScript.src = 'file2.js';
oScript.type = 'text/javascript';
oScript.onload = function() {
    console.log(message);
};
document.body.appendChild(oScript);

Or:

oScript = document.createElement('script');
oScript.src = 'file2.js';
oScript.type = 'text/javascript';
oScript.addEventListener('load', function() {
    console.log(message);
});
document.body.appendChild(oScript);

1 Comment

oh! thank you so much. I was able to use your example and make my script work. Thank you very much for your explanation.

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.