Loading images synchronously with javascript Loading images synchronously with javascript ajax ajax

Loading images synchronously with javascript


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.


I don't think you can do it asynchronously, and think it would be very risky if the path to the image file is wrong.You must consider that onload is a callback, that will be called when the image is fully loaded.

So you have to execute the all drawing code in the callback function.