开发者

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

开发者 https://www.devze.com 2022-12-28 07:16 出处:网络
var img=new Image(); img.src=\'xxxxx\'; Wi开发者_JS百科ll the browser wait for the image to load then execute the next code line? That action is asynchronous; a lot of image \'pre-loading\' code rel
var img=new Image();
img.src='xxxxx';

Wi开发者_JS百科ll the browser wait for the image to load then execute the next code line?


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';


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.


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


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

0

精彩评论

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