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

5
  • 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. Commented Mar 15, 2012 at 6:19
  • this is not the real code, i changed the filenames and file2.js, yes is a little large.. Commented Mar 15, 2012 at 6:21
  • 1
    Check this: stackoverflow.com/questions/950087/… Commented Mar 15, 2012 at 6: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 Commented Mar 15, 2012 at 6: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! :)) Commented Mar 15, 2012 at 6:42

2 Answers 2

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.

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

1 Comment

thanks for this! you're right i should wait before its loaded.. I followed the answer of the link that Sudhir provided! thanks guys!
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**

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.