My image is loading, but its height and width have not yet been updated. When does this happen?

I am using a jQuery plugin that calls a callback after loading all the images on the page. It checks the imageObject.complete property and binds the handler to the load and error events to determine when the image is loading.

This works well, but the problem I am facing is that although the image is considered loaded when I check the height and width properties of the image or its div element, the dimensions are not updated yet.

Here is an example:

http://jsfiddle.net/RtnVx/12/

How can I make sure that the containing element has been resized to fit the image before trying to access its height and width dimensions?

EDIT 1: I cleaned up and commented out the code in my jsfiddle to make this example clearer.

EDIT 2: There must be a race condition or a cache-based variation, because when I run the code from another computer, it works correctly (i.e. the top field is calculated correctly), which is actually not good , because it is incompatible. Inconsistencies are more apparent in Chrome, FWIW.

Furthermore, to be clear, the goal is not to invoke init every time the image is loaded; rather, init should be called once after loading all images using an AJAX load call.

+4
source share
1 answer

Answer: http://jsfiddle.net/morrison/RtnVx/30/

You did not need to call batchImageLoad before loading the image. I created an event on the uploaded image.

Updated notes:

  • I disabled your jQuery plugin. It was too complicated, and I did not quite understand it.
  • My current solution provides error handling with the error event, as does the plugin.
  • Decision Process:
    • Find all img descending from #slides and save that length in the .data() attribute, as well as a variable to save how many of them were loaded.
    • Bind the load and error events to each img that updates the number of loaded images.
    • If the number of loaded / erroneous images reaches the total number of images, call setTimeout() until all of them have a width greater than zero, then fire init() .
+3
source

All Articles