0

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!

user1856596
  • 7,027
  • 10
  • 41
  • 63

2 Answers2

1

you can do

if (myfunction != undefined)
{
}

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

if(typeof (window.myFunction) == ‘function’) {
Smeegs
  • 9,151
  • 5
  • 42
  • 78
1

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);
Gabe
  • 49,577
  • 28
  • 142
  • 181