Question

I'm having an issue with centering some images that are loaded to an absolute position (previously set by customer team).

I've traced the problem to getting an elements height.

An image is appended and if I try to get its height immediately after, it's returns 0. I did some testing with setTimeout and narrowed it down to a 17 ms (on my system) delay for the height to return correctly.

How can I work around this without using the setTimeout function, each computer the webapp is run on will have a different delay time?

Était-ce utile?

La solution

Those 17ms are your browser downloading and parsing the image!

Do your formatting on the load event for the image, since the browser doesn't know how big the image is until after it is loaded. For example:

var $img = $('<img src="' + image_source + '"/>');
// The browser might not load the image unless it is attached to the DOM
$('#image_container').append($img);
$img.on('load', function() {
    // Now we know how big the image is
    update_my_ui($img.height());
});

You could always preload the image off-screen if you don't want the UI to jump around when the file loads. I have heard, unfortunately, that when images load from cache in older browsers, you may not get a load event fired, so you may want to investigate that further.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top