Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
720 views
in Technique[技术] by (71.8m points)

ajax - jquery .getscript() callback when script is fully loaded and executed

As from the jquery api page http://api.jquery.com/jQuery.getScript/

Success Callback

The callback is fired once the script has been loaded but not necessarily executed.

$.getScript("test.js", function() {
    foo();
});

if the foo() function depend on test.js, it cannot be execute successfully.

I saw similar thing with google map api but in that case you can specify the callback function in the ajax script url. But in general is there an obvious way to wait until the ajax script executed to do the callback?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I know it is an old question but i think both answers containing "done" are not explained by their owners and they are in fact the best answers.

The most up-voted answer calls for using "async:false" which will in turn create a sync call which is not optimal. on the other hand promises and promise handlers were introduced to jquery since version 1.5 (maybe earlier?) in this case we are trying to load a script asynchronously and wait for it to finish running.

The callback by definition getScript documentation

The callback is fired once the script has been loaded but not necessarily executed.

what you need to look for instead is how promises act. In this case as you are looking for a script to load asynchronously you can use either "then" or "done" have a look at this thread which explains the difference nicely.

Basically done will be called only when a promise is resolved. in our case when the script was loaded successfully and finished running. So basically in your code it would mean:

$.getScript("test.js", function() {
    foo();
});

should be changed to:

$.getScript("test.js").done(function(script, textStatus) {
    console.log("finished loading and running test.js. with a status of" + textStatus);
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...