1

I have a script which fades in an image when it is loaded to prevent ugly loading animations, which uses the $(elem).load(); function.

My problem is that sometimes there will be a couple of images on the page which haven't been faded in. This is supposedly because the load event hasn't been triggered. I've checked the console for errors, but nothing can be found... It doesn't always happen, but it does on the occasional request.

The Script:

// Function to be applied to any element
jQuery.fn.preFade = function( speed, callback ) {
    this.load(function(){
        $(this).fadeIn(speed, callback);
    });
};

// The .prefade class has display: none; applied to it in my CSS
$(document).ready(function(){
    $('.prefade').preFade(1000);
});

The thing that stumps me the most is the fact that although the load event isn't triggered, the image is actually loaded. The reason I know this is because when I inspect the element, and change it to display: block; from display: none; the image appears.

I have an inkling there is perhaps something I am missing with the order in which events are called...

SixteenStudio
  • 986
  • 9
  • 22

2 Answers2

5

I was linked to a solution in the comments, this is how it fit into my code.

this.one('load', function(){
    $(this).fadeIn(speed, callback);
}).each(function(){
    if (this.complete) { $(this).load(); }
});

Changing from the simple $.load() function (which uses $.on('load')) to the $.one('load') function restricts the event to only firing once. if (this.complete) then checks whether it has been loaded before the event has even been binded to the element, and if it has, it will trigger the load event.

Link to solution

Community
  • 1
  • 1
SixteenStudio
  • 986
  • 9
  • 22
0

Use $(window).load event. This will only be trigered when all images are loaded

$(window).load(function(){
    $('.prefade').preFade(1000);
});
Joao Almeida
  • 902
  • 2
  • 6
  • 15