$(document).ready() versus $(window).load()

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 <article> 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).

	//will report lesser because images above not loaded


	//will report higher since images will be loaded

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s