2

This may be a very easy and novice question, and I'm not even sure if the asynchronous call is the one to blame. But anyway...

I'm using jQuery and its function to add external scripts on a .php file. First, let's have a look at my external js. (test.js):

function testFunc () {
  alert('It works!');
}

Then I have my .php file with this script:

<script>
$.getScript('supervisor/cache/test.js');
$(document).ready(function() {
  testFunc();
});
</script>

Using this method, the testFunc(); is not called. I tried inserting return before the call, putting it outside the ready function, putting the $.getScript inside the ready function. Well, I don't know what else to try. Also, if I call this same function using the onClick in a button, it will work. That's why I think the problem may be with the Asynchronous call from jQuery, that is executing my function before the script is really added. But who knows? Anyone had the same problem before?

2
  • 2
    @tylermwashburn: I assumed he outputs that script via PHP as part of the website. Commented May 26, 2011 at 18:13
  • @tylermwashburn I think that he meant that the JavaScript shown is produced by the .php code. Commented May 26, 2011 at 18:14

2 Answers 2

5

You should invoke the function once the AJAX script has finished executing which could happen much later than the document ready event:

$.getScript('supervisor/cache/test.js', function() {
    testFunc();
});
Sign up to request clarification or add additional context in comments.

Comments

2

Since you are retrieving the script asyncronously, the document is probably ready before test.js is loaded. Do this instead:

$.getScript('supervisor/cache/test.js', function(){
    testFunc();
});

2 Comments

same as @darin. he and I must have been writing our answers at the same time.
So you also deserve a +1, as this is not the Wild West where the fastest hand wins :)

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.