My image is done loading, but its height and width have not yet been updated. When does this happen?
I'm using a jQuery plugin that invokes a callback once all images on page have been loaded. It checks the imageObject.complete
property and binds a handler to the load
and error
events to determine when image loading is done.
This works well, but the problem I'm running into is that, even though an image is considered loaded, when I inspect the height
and width
properties of the image or its containing div
element, the dimensions have not yet been updated.
Here's an example:
http://jsfiddle.net/RtnVx/12/
How can I ensure that the containing element has been resized to fit the image before attempting to access its height
and width
dimensions?
EDIT 1: I cleaned up and commented the code in my jsfiddle to make the example easier to understand.
EDIT 2: There must be a race condition or variation based on caching because when I run the code from a different machine, it works properly (i.e., the top margin is calculated properly), which is actually not good because it is not consistent. The inconsistencies are more apparent in Chrome, FWIW.
Also, to be clear, the goal isn't to call init
every time an image loads; rather, init
should be called once after all images have been loaded via the 开发者_开发知识库AJAX load
invocation.
Answer: http://jsfiddle.net/morrison/RtnVx/30/
You needed to not call batchImageLoad
until the image was done loading. I created an event on the loaded image.
Updated Notes:
- I cut out your jQuery plug-in. It was overly complex and I didn't completely understand it.
- My current solution provides error handling by using the
error
event, as did the plug-in. - The solution process:
- Find all the
img
's descending from#slides
and store that length in a.data()
attribute, as well as a variable to keep how many have loaded. - Bind a
load
anderror
events on eachimg
which updates the count of loaded images. - If the count of loaded/errored images hits the total image count, call
setTimeout()
until all of them have widths greater than zero then fireinit()
.
- Find all the
精彩评论