Reputation: 323
I am trying to call an external js file from another js file. Here is my code:
file1.js
function func1(id){
var NewScript= document.createElement('script')
NewScript.src="file2.js"
document.body.appendChild(NewScript);
func2(id);
}
file2.js
function func2(id)
{
alert("im here " +id);
}
But when I ran it it gives out the "func2 is not defined. " Am i doing it right?
Can somebody help me?
Thanks
Upvotes: 1
Views: 4911
Reputation: 81
import1.js:
var a = function () {
console.log( 'function a' );
this._require(function(){
b( 123456 );
});
};
a.prototype._require = function (callback) {
var xhr = new XMLHttpRequest();
xhr.onload = function (e) {
var script = document.createElement('script');
script.innerHTML = e.target.responseText;
document.getElementsByTagName('head')[0].appendChild(script);
callback();
};
xhr.open('GET', 'import2.js', true);
xhr.send();
};
new a();
import2.js:
var b = function ( id ) {
console.log( id );
};
result:
Upvotes: 0
Reputation: 360562
You have to wait for the script to actually be loaded/parsed. .appendChild will return immediately and your code continues on, likely LONG before the browser's had a chance to fetch the new script.
Moving from .appendChild() to func2() in the code is likely to be milli or microseconds, while fetching the script could be entire seconds, depending on how lossy/laggy the network is acting at that time.
Upvotes: 1