user1856596
user1856596

Reputation: 7233

Checking if JavaScript is loaded in an Ajax call?

I am adding a JavaScript file to my site (using appendChild) in an Ajax calls oncomplete. After that I am trying to call a function that is included in that file. Like this:

// append the JS to the head
document.getElementsByTagName('head')[0].appendChild(element);

// call a function that is contained in the js file
myFunction();

The call to myFunction says "myFunction() is not defined". The question is, how do I know when it is defined?

Thanks!

Upvotes: 0

Views: 87

Answers (2)

Gabe
Gabe

Reputation: 50493

You can use onload to find out when it's complete.

var s = document.createElement('script');
 s.onreadystatechange = s.onload = function() {
    var state = s.readyState;

    if (!callback.done && (!state || /loaded|complete/.test(state))) {
        // done!
    }
};
s.src = "myurl/myscript.js";
document.getElementsByTagName('head')[0].appendChild(s);

Upvotes: 1

Smeegs
Smeegs

Reputation: 9224

you can do

if (myfunction != undefined)
{
}

Also to make sure it's a function you can add this

if(typeof (window.myFunction) == ‘function’) {

Upvotes: 1

Related Questions