As a force of habit, I’ve always just wrapped my JavaScript code in a $(document).ready() and assumed/hoped for the best. I know that this is specifically for when the DOM is ready, and doesn’t have anything to do with images.  However, 99% of the time I’ve never really been concerned about the status of loaded images.

Today, I came across an issue where during the $(document).ready() I needed to get the TOP position property of an

element.  The number coming back was too low, like 100px, even though I knew the article started more like 500px down the page.  The culprit was a large (400px ish tall) hero image that was loading slowly (well slower than the document was ready).  Because the image wasn’t loaded, and because I was using $(document).ready() the top that was being reported was in fact correct.  It only changed after the image was fully loaded.

So instead, I found a post mentioning the use of $(window).load() (which works exactly the same way as $(document).ready()) but instead waits until EVERYTHING is ready: images, frames, etc.  Having my code execute inside $(window).load() caused my position top to be reported correctly (since it waited until after that tall hero image was done loading).

[sourcecode language=”javascript”]

$(document).ready(function(){

console.log($(‘article’).position().top);

//will report lesser because images above not loaded

});

[/sourcecode]

Versus…

[sourcecode language=”javascript”]

$(window).load(function(){

console.log($(‘article’).position().top);

//will report higher since images will be loaded

});

[/sourcecode]

comments powered by Disqus