Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

async or sync ? when we set the src property of the Image object?

Tags:

javascript

var img=new Image();
img.src='xxxxx';

Will the browser wait for the image to load then execute the next code line?

like image 947
lovespring Avatar asked Apr 22 '10 13:04

lovespring


4 Answers

That action is asynchronous; a lot of image 'pre-loading' code relies on that feature.

EDIT: To give a little bit more useful information as well. If you're wanting to have certain actions synchronously wait for images to load via javascript's image object, you can use the onload event, like so:

var img = new Image();
img.onload = function () { /* onLoad code here */ };
img.src = 'xxxxxx';
like image 82
Dereleased Avatar answered Nov 16 '22 12:11

Dereleased


Changing src is asynchronous.

The code

image.src = "http://newimage-url";

will return immediately and the browser will load new image in another thread. Before it's fully loaded, all attribute of that <img> tag won't be correct, such as width or height.

So $(image).width() may not return the new image's width.

As @Dereleased pointed out, you can implement a 'on load' method, which code will be executed only after the image has finished loading. jQuery's load() can fulfill this easily.

like image 30
luanjunyi Avatar answered Nov 16 '22 11:11

luanjunyi


var img=new Image();

This is the old way of creating images, which has been deprecated. Prefer document.createElement('IMG') or create one through strings and innerHTML.

Now, images are replaced elements, which means they load whenever they arrive, but space is reserved for them in the layout flow if their dimensions are specified. (If not, an icon-sized space is reserved and the screen is redrawn when the image arrives with its dimensions in the header; this can be a disconcerting user experience, so you are encouraged to have image dimensions ready while the page is being rendered the first time.)

like image 41
Robusto Avatar answered Nov 16 '22 13:11

Robusto


Agree with @dereleased image pre-loading is done asynchronously; just thought I'd add that there are a number of ways to use this technique on the Image() object in javascript, like using arrays or event handlers.

https://web.archive.org/web/1/http://articles.techrepublic%2ecom%2ecom/5100-10878_11-5214317.html

like image 1
amelvin Avatar answered Nov 16 '22 13:11

amelvin