Dont rely on .load()
function for images.
Even jQuery says so .
Caveats of the load event when used with images
A common challenge developers attempt to solve using the .load() shortcut is to execute a function when an image (or collection of images) have completely loaded. There are several known caveats with this that should be noted. These are:
It doesn't work consistently nor reliably cross-browser It doesn't fire correctly in WebKit if the image src is set to the same src as before It doesn't correctly bubble up the DOM tree Can cease to fire for images that already live in the browser's cache
Read here
If you can , use this,
$(window).load(function(){
// Images are now loaded for sure
})
Edit:
or use Paulirish's very lite jQuery plugin
imageLoaded
.load()
can be a tricky one, but something like this should work (notice the this.complete check):
jQuery('.my-image').each(function(){
$(this).load(function(){
jQuery(this).greyScale({
fadeTime: 200,
reverse: false
});
$(this).animate({ 'opacity' : 1 }, 1000);
});
if (this.complete) {
$(this).trigger('load');
}
});
Try to avoid duplicating code, it's not the best of practice.
A good way to test whether an image has loaded or not is to try and access its dimensions, if you can get the height or width of an image, you can assume it has loaded and greyscale it. Therefore you could modify your code to do this:
jQuery('.my-image').each(function()
{
var greyscale = function(image)
{
jQuery(image).greyScale({
fadeTime: 200,
reverse: false
});
}
if ( jQuery(this).width() )
{
// it's loaded, greyscale its ass
greyscale( this );
}
else
{
// wait for the load
$(this).load(greyscale);
}
});
In this situation, since you want the image to be greyscale first I'd recommend inserting images programmatically:
Where your <img>
tags would be, replace them with <div>
tags where you add a data-src
attribute, this will contain the image's URL.
When you're document has loaded, use a script that goes through all the <div>
tags and insert the <img>
tags within the <div>
tags, for example:
jQuery('div.my-image').each(function()
{
var el = jQuery( this );
// get the src for the image
var src = el.data( 'src' );
// start loading the image
var img = new Image();
img.onload = function()
{
// greyscale it
jQuery(img).greyScale({
fadeTime: 200,
reverse: false
});
// append it
el.append( img );
}
// load the image by setting the src
img.src = src;
});