Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loading images synchronously with javascript

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?

like image 875
devongovett Avatar asked Jul 19 '09 12:07

devongovett


2 Answers

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.

like image 122
David-SkyMesh Avatar answered Oct 24 '22 05:10

David-SkyMesh


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.

like image 21
Keith Bentrup Avatar answered Oct 24 '22 03:10

Keith Bentrup