1

I'm creating a big page with a lot of blocks containing big background images, so I thought the best thing would be to show a preloader and load images in the background and update the loader (image 4 of 20, ecc). My problem is: when the onload event fires my loader diasppears but I still see the image loading, this means it wasn't completely loaded. Why does this happen? any idea?

here's the page:

http://zhereicome.com/experiments/statics/myascensor/#1-1

Thanks in advance

nImages = $('.slide').length;
loadedImgs = 0;
var bgImages = ['img/bbb.png','img/bbb2.png','img/bbb3.png'];

$('.slide').each(function(i){
    var curSlide = $(this);
    var img = new Image();
    img.src = bgImages[ i % 3 ];
    img.onLoad = imageLoaded(img, curSlide);
})    

function imageLoaded(img, curSlide){
    curSlide.css('backgroundImage', 'url(' + img.src + ')');
    loadedImgs++;
    if(nImages == loadedImgs){
        $('#container').css('visibility','visible');
        $('#loader-cont').fadeOut(1000);
    }
    $('.loader-inner .title').text(loadedImgs / nImages);
}
Jonas Grumann
  • 10,438
  • 2
  • 22
  • 40
  • Also, the pattern is img.onload = someFunc; _THEN_ img.src = someFile; You have to tell it what to do when the file loads before you try to load it. If the image is already cached, you can easily not have the onload event fired. It may 'work'(mostly) but it is not the right approach. – enhzflep Oct 29 '12 at 16:47

1 Answers1

1

You seem to have some trouble with window.onload and document.ready:

$(document).ready(function(){
// This will be executed when the DOM is ready.
});

$(window).load(function(){
// This will be executed when the whole document and all its 
// referenced items (style sheets, scripts, images, etc.) are loaded.
});

But this has been asked before and answered much, much better: How can I create a "Please Wait, Loading..." animation using jQuery?

Community
  • 1
  • 1
NotGaeL
  • 8,344
  • 5
  • 40
  • 70
  • 2
    thanks elcodedocle, but adding a loading animation and remove it on window load is not what I'm looking for. What I wanted was a loading screen WITH a percentage. Anyway, I solved like this: $(img).load(function(){ curSlide.css('backgroundImage', 'url(' + img.src + ')'); loadedImgs++; if(nImages == loadedImgs){ $('#container').css('visibility','visible'); $('#loader-cont').fadeOut(1000); } $('.loader-inner .title').text('loading...' + ((loadedImgs / nImages) * 100) + '%'); }) – Jonas Grumann Oct 29 '12 at 20:48