1

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

tinks
  • 323
  • 1
  • 5
  • 21
  • Is this a hypothetical example you're trying and it's not working or that's your real code? Because if your file is quite large you need to wait for the browser to load the new JS file. – Strelok Mar 15 '12 at 06:19
  • this is not the real code, i changed the filenames and file2.js, yes is a little large.. – tinks Mar 15 '12 at 06:21
  • 1
    Check this: http://stackoverflow.com/questions/950087/include-javascript-file-inside-javascript-file – Sudhir Bastakoti Mar 15 '12 at 06:21
  • As Mark suggested, you have to wait for the script to be loaded and parsed. To test what Marc B is saying, Try calling func2('test') in Body's onload and that will work – kalyang Mar 15 '12 at 06:37
  • thanks @Sudhir!!! and thanks all for replying! you guys are great! :D its okay already. i followed the answer in the link that sudhir provided! :)) – tinks Mar 15 '12 at 06:42

2 Answers2

1

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.

Marc B
  • 356,200
  • 43
  • 426
  • 500
  • thanks for this! you're right i should wait before its loaded.. I followed the answer of the link that Sudhir provided! thanks guys! – tinks Mar 15 '12 at 06:43
0

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:

**result**

K2Spam
  • 81
  • 1
  • 3