This has to have been asked many time but a search didn't return anything with "synchronous" in the name.
I need to load images before they are displayed. I have made this work in the past but then using what appears to be the same method again doesn't work.
I have something like this.
Code:
function loadImage(path)
{
function loadImg(image)
{
if (image.complete>0)
{
alert(image.complete);
return true;
}else
{
setTimeout(function(){loadImg(image)},200);
}
}
var preImage=new Image(0,0);
preImage.src=path;
loadImg(preImage);
return false;
}
function doSomething
{
loadImage(path);
alert("Complete");
}
Complete is always returned before the load is complete. So, is there an understandable way to make the doSomething function wait until the load of the image is complete?
I have searched for answers that I get the most convoluted solutions and none of them have decent explanations or at least not for me.
you can add onload events to each preloaded image, and fire complete once all of the callbacks have fired, but it's easier to use window.onload; it fire when all the images are loaded.
//global somewhere:
var waiting=0;
//// modifed from post #1:
var preImage=new Image(0,0);
waiting++
preImage.onload=function(){ waiting--;};
preImage.src=path;
loadImg(preImage);
return false;
You can simplify if you don't need to dynamically set the returnFunction and just write everything in img.onload = function(){YOUR STUFF HERE} and get rid of the 2nd argument in loadImg.
Bookmarks