开发者

Asynchronous JavaScript doesn't let my function return?

开发者 https://www.devze.com 2023-03-08 10:46 出处:网络
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...

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>
$.getSc开发者_运维百科ript('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?


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();
});


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();
});
0

精彩评论

暂无评论...
验证码 换一张
取 消