This particular issue is causing frustration as it seems to only work with a specific set of images and not with others.
The object in question is:
function PreLoader(toLoad, parent, images) {
var errored = 0;
var loaded = 0;
var toLoad = toLoad;
function allLoaded() {
// reset the counters so it can be used again
loaded = 0;
errored = 0;
// determine which img is the tallest
var l = 0;
for (var i = 0; i < images.length; i++) {
l = (l > images[i].height()) ? l : images[i].height();
}
// set the height of the container to the tallest
// unless it's already bigger
// height() is from jQuery
if (parent.obj.height() < l)
parent.obj.css("height", l);
}
this.load = function() {
++loaded;
if (loaded + errored == toLoad)
allLoaded();
};
this.error = function() {
++errored;
if (loaded + errored == toLoad)
allLoaded();
};
}
The method of implementation has been similar to the following:
var parent = {obj: $("#some-img-container")};
var slabLoader = new PreLoader(2, parent, [external.slab, internal.slab]);
external.slab.src = "2.png";
external.slab.onload = slabLoader.load;
external.slab.onerror = slabLoader.error;
internal.slab.src = "1.png";
internal.slab.onload = slabLoader.load;
internal.slab.onerror = slabLoader.error;
The challenge arises when this approach does not consistently provide the desired outcome. There are multiple image sets that are absolutely positioned due to being layered on top of each other, resulting in varying heights. Hard coding the heights is not feasible as they are unknown prior to page load, and absolute positioning does not impact their parent elements' size, making methods like height: 100%
unreliable.
In certain instances, the variable l
in the allLoaded()
function returns 0 even though the images should have finished loading by then.
Is my assessment accurate or am I overlooking something that could explain why it occasionally succeeds?
The corresponding HTML structure appears as follows:
<div class='wrapper-hover'>
<div class='wrapper-content'>
<a herf='#' id='some-img-container' class='viewport'>
<!-- this is where the image goes, added by the script -->
</a>
<div class='wrapper-caption'>
<label class='wrapper-caption-content'>Some Image</label>
</div>
</div>
</div>
I apologize if the inquiry is somewhat challenging to decipher.
UPDATE:
Using .naturalHeight
instead of jQuery's .height()
retrieves the actual image height on disk rather than its scaled CSS height (width: 100%
) but still fails to address the zero height returned for some images previously.
All images indicate .complete
as true before attempting to access their heights.