absentx
absentx

Reputation: 1417

How do I count images as they are loading in Chrome with Javascript?

I have about four hundred images on a page and I want to show the user an increment counter of the images as they load on the page. It is working in Firefox nicely but I am having trouble with IE and Chrome.

var increment ={
    start: function(){
        $updateThree = $('.container').children('img').length;
        increment.countImagesLoading();
        getCount =  setInterval(increment.updateImagesLoading,100);
    },//end function
    countImagesLoading:function(){
        imgCount = 0;
        $img = $('.container').children('img');
        $img.one('load',function() {
          imgCount++;
      });
    },
    updateImagesLoading: function(){
      $colThree.html('<strong>'+imgCount+'</strong>');  
      if(imgCount == $updateThree){
         clearInterval(getCount);
         //end the interval because all the images are loaded!
      }
    },
}

$(document).ready(increment.start);//document.ready

I have also removed the interval and the call to updateImagesLoading and just had the countImagesLoading function update the value on screen with each .load function too, but regardless of which method I use I still get the same results:

Firefox, it works. Chrome, it works but ends up being fifteen to twenty short from the true count of images that should load on the page (464). IE, doesnt display the count update as it should via $colThree.html('<strong>'+imgCount+'</strong>'); until all images are completely loaded, so its sits blank and then displays 464.

Upvotes: 2

Views: 1237

Answers (1)

Parv Sharma
Parv Sharma

Reputation: 12705

here i think the problem is that this script gets executed on the ready event but the images start to load as soon as they are found in the DOM.

the problem should resolve if you can somehow change the src of all the images to one single loading image and put the actual src in some other attribute say data-src. then on the ready event take up each pic and load the pic taking the url from the data-src attribute. when its loaded fully in JS ser the url of the pic.

$('img').each(function(){
 var src = $(this).data('src');
 var img = new Image();
 img.load = function(){
  /*increase count here and set the src of the DOM img element*/
  };
 img.src = src;
});

Upvotes: 1

Related Questions