1

I created the following testpage: http://methodus.de/wp/

It gets the dominant colour of the images of each blog post and use them for animation when scrolling down the page. Unfortunately, the colour can't be calculated as long as the image isn't fully loaded (see the javascript alert). The animation doesn't work then. When I reload the page, the images where cached by the browser, and everything works like charme.

The relevant code is:

    $('.bg').each(function(index) {
        var url = $(this).data('background-image');
        img = new Image();
        img.src = url;
        averageColours[url] = getAverageColourAsRGB(img);
        $(this).css('background-image', 'url(' + url + ')');
    });

    $('.bg').waypoint(function() {
        var url = $(this).data('background-image');
        var colour = getPreloadedAverageColourAsRGB(url);
        console.log(url + ' ' + colour.r + ',' + colour.g + ',' + colour.b);
        $('body').data('bgColour', 'rgb(' + colour.r + ',' + colour.g + ',' + colour.b + ')');
        $('body').animate({backgroundColor: $('body').data('bgColour')});
    }, { offset: 0 });

How can I postpone the waypoint binding until the images where fully loaded?

Denis Loh
  • 2,194
  • 2
  • 24
  • 38

1 Answers1

2

There are some hacky ways to do this using $.load, but at the moment the best approach that i've found is to use imagesloaded.

You could then do something like:

$('.my-content-class').imagesLoaded( function() {
  // ... your code here
});
Nick Tomlin
  • 28,402
  • 11
  • 61
  • 90
  • This post http://stackoverflow.com/questions/5057990/how-can-i-check-if-a-background-image-is-loaded worked for me, though I still don't understand, why I have to create a img element for that. What's the differents between the img-Element and new Image()? Both have an onload() callback. – Denis Loh Nov 27 '13 at 21:04