tags:

views:

36

answers:

3

var img=new Image();
img.src='xxxxx';
//will the browser wait for the image then exec the next code line?

+4  A: 

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';
Dereleased
+1  A: 

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.)

Robusto
Deprecated? Really? I don't believe it was ever part of any standard in the first place.
Tim Down
@Tim Down: I just mean that this is the old (c. 1990s) way of creating images, which is not part of current practice.
Robusto
`new Image()` continues to work in every scriptable browser that supports images, and I would favour it over `innerHTML`. Agreed that `document.createElement("IMG")` is preferable.
Tim Down
+1  A: 

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.

http://articles.techrepublic.com.com/5100-10878_11-5214317.html

amelvin