开发者

how to execute code inside of image onload function before returning the result?

I want to return code executed inside of image onload function. The code is :

function loadImage() {
  var data = null;
   var image = new Image();
   image.onload = function() {
     console.log("I am inside of image load function");
     data = "I am inside";
   }
   image.src="flower.jpg";
   console.log("I am outside of image load function");

   console.log(data);
   return data;
}

And the result in firefox console is :

I am outside of image load function
null
I am inside of image load fun开发者_运维知识库ction

What i want is, the above code should return the value of data assigned inside of image onload function i.e. i want the returned data to be "I am inside". i.e.

I am inside of image load function
I am outside of image load function
I am inside

What to do get to the desired result ?

or

How to execute the code inside of the image onload function first and then only outside of the function ?


I'm guessing that the example above is a boiled down sample of something else?

Not quite sure what you're trying to achieve but looking at your code do you understand why the null comes where it does?

data maybe null at the the point console.log(data) is executed because the image hasn't finished loading.

What do you want to happen when the image loads and can't you make it happen from within the unload even handler?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜