Reputation: 5585
I'm using jquery load()
to load multiple items. All works good.
for(i = 0; i<item.length; i++){
$( '#parent'+i).load('file'+i+'.html',function(){
customFunctions();
});
}
My question is, I need to run customFunctions()
when all completes loading. My above code runs it multiple times. How can I run customFunctions()
once only after all files complete loading?
Upvotes: 1
Views: 240
Reputation: 11994
It is about making promises, but you could also do this:
var all_loaded = 0;
for(var i = 0; i < item.length; i++){
$( '#parent' + i).load('file' + i + '.html',function(){
++all_loaded == item.length && customFunctions();
});
}
//++all_loaded: mean It is sum +1 when a file is loaded
So when all_loaded
is equal to item.length
, the function is loaded just at the end.
Upvotes: 4
Reputation: 702
There are a number of options.
You can just keep track in your loop:
var loadedCount = 0;
for(i = 0; i<item.length; i++){
$( '#parent').load('file.html',function(){
loadedCount++;
if (loadedCount === item.length) {
customFunctions();
}
});
}
That will get the job done for this specific case. This only works in this constrained design where you know how many times you are calling and can trust/believe that none of your AJAX requests will fail. As a result, it is not a very stable design.
Upvotes: 0
Reputation: 4224
Try This:
Your function will run only if all load request is successful
var item = {length:12};
runfunction = 0;
for(i = 0; i<item.length; i++){
$( '#parent').load('t.html',function(responseText, textStatus, XMLHttpRequest){
if (textStatus == "success") {
runfunction++;
}
/* you can write three line of code any where even after for loop according to your requirements*/
if(runfunction == item.length ){
customFunctions();
}
});
}
function customFunctions(){
alert(1);
}
Upvotes: 0
Reputation: 1240
Add counter and update it when each file is loaded. When current value of counter will be equal to total files count you want to load, then call your function;
Upvotes: 1
Reputation: 1946
for(var i = 0; i<item.length; i++){
$( '#parent').load('file.html',function(){
if(i==(item.length-1))
customFunctions();
});
}
This should work.
Upvotes: 0