Reputation: 7233
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
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
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