jQuery: Fade Images In On Load

Normally in jQuery, you put all of your code in the following block of code:

$(document).ready(function() {  
    // Stuff to do as soon as the DOM is ready;  

and that allows you to make sure everything's in the DOM before you start manipulating it.

However, images bring a special case. Images are not guaranteed to be loaded when $(document).ready() is triggered.

For me, the issue seems to be much more prominent in Chrome. All images usually return a width and height of 0, etc, if its width/height isn't explicitly set. What's more, is containers that grow with their content won't return the correct height if any images are inside.

The relatively lesser known solution is the following block of code:

$(window).load(function() {  
    // Stuff to do as soon as all of the images (all resources, actually) are loaded;  

So if you need the height or something of an image, wrap it in a $(window).load().

But let's say you want to fade in each individual image as soon as it's done downloading (and don't necessarily care about its height/width or it's explicitly set), you can actually attach the load function to an individual image, and that function will be triggered as soon as that one image is down downloading. If done correctly, you can get a cool effect where an image-heavy page has each image fade in at a slightly different time.

img {  
// bind .load() to each image when the DOM's ready  
$(document).ready(function() {  
    // fade in each image individually as it's downloaded  
    $('img').load(function() {  

It's as simple as that. I get people asking every once in a while how to do this, and after looking at some other very complicated solutions, it doesn't get much easier than this. I've seen it to achieve some pretty sweet visual effects. Just remember that an element with display:none also has no height and width.

DEMO | Demo with HUGE IMAGES (average image size > 2MB, so the effect is exaggerated, but can take a while to download altogether depending on internet speeds.)