Reputation: 5821
Lets say I have the following js code
$(function() {
$('#some_id').load('myfile.html', function() {
alert('Call back called');
});
alert('You should alert second');
// more javascript code .........
});
For some reason, alert('Call back called');
is the last thing that gets alerted to me. I thought that js code executes in the order of the file. Is there a way to make alert('Call back called');
go first before all my other functions.
Looking at my simple code snippet one would suggest why not put alert('You should alert second');
in the function call back, unfortunately I am inheriting a code base that is really big and jamming all those function calls in my callback wont be feasible
Upvotes: 0
Views: 1054
Reputation:
You could use the Deferred Object which deals with asynchronous calls for you. Doing so your code will be executed in the reading order, no matter when the response is sent back :
$(function() {
var jqxhr = $.get('myfile.html', function(data) {
$('#some_id').html(data);
alert('Call back called');
});
jqxhr.done(function() {
alert('You will alert second');
});
});
Upvotes: 1
Reputation: 10244
Using pure javascript, just add a function with a callback argument for the stuff coming in the second alert()
area:
$(function() {
function someCode (callback) {
$('#some_id').load('myfile.html', function() {
alert('Call back called');
// add parameters, if you like
callback();
});
}
function someMoreCode() {
alert('You should alert second');
// more javascript code .........
}
// And Finally...
someCode(someMoreCode);
});
Upvotes: 1
Reputation: 5126
As pointed by others, load is an async method, hence you need to use something like a synchronous AJAX call. Use it this way:
$.ajax({
url: 'myfile.html',
async: false
success: function(result) {
alert('Call back called');
}
});
alert('You should alert second');
Upvotes: 1
Reputation: 2385
"I thought that js code executes in the order of the file." It does, and that's what's happening here. But because the .load()
callback function is, well, a callback (i.e. only fires once the asynchronous operations is complete) alert('Call back called');
will only fire when it's invoke at some point in the future.
Upvotes: 1
Reputation: 4146
If you want alert('You should alert second');
to happen second you need to call it from within your callback function:
$(function() {
$('#some_id').load('myfile.html', function() {
alert('Call back called');
alert('You should alert second');
});
});
Upvotes: 0
Reputation: 7898
.load()
is an asynchronous method, and the anonymous function you passed to it as a parameter is executed ONLY when the asynchronous method finishes executing.
Upvotes: 2