I need to load an image synchronously, that is I need to pause execution of javascript until the image is loaded. Since image.onload is asynchronous, the main function will return before the image is loaded.
I am using canvas, and if the main function returns before the image is loaded, and therefore drawn, other things in the canvas will be drawn before the image. This does not work because the order of drawing on a canvas is very important!
Here is what I've been doing:
var img = new Image();
img.onload = function() {
//image drawing code here
}
img.src = "blahblahblah";
//function returns here, and other drawing code happens before image is drawn
Is there a way to do this synchronously, or to wait until the image is fully loaded before returning from the function?
Is there a way to do this synchronously, or to wait until the image is fully loaded before returning from the function?
No. AFAIK, the only thing that can be done synchronously in Javascript is a synchronous XHR call.
In any case, what you should be really doing is setting up a heirarchy of callbacks which implement your dependencies.
Can't this be solved by refactoring?
Wrap whatever code you need to execute after the image load into a function invoked by the callback (or make that function the callbak).
I see that you say that if the main function returns, other code will execute. Can you wrap that, too? Can you delay it's execution or make it dependent on this onload event or someother event?
You could even dynamically load the source of the other javascript code in the image onload.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With