Loading images synchronously with javascript

后端 未结 3 1150
清歌不尽
清歌不尽 2021-01-04 21:48

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

相关标签:
3条回答
  • 2021-01-04 21:55

    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.

    0 讨论(0)
  • 2021-01-04 22:07

    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.

    0 讨论(0)
  • 2021-01-04 22:08

    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.

    0 讨论(0)
提交回复
热议问题