Reputation: 35
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"}];
Upvotes: 1
Views: 88
Reputation: 60527
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);
Upvotes: 0
Reputation: 12577
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.
Upvotes: 1