如何在使用Javascript加载Chrome时计算图像

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

本文关键字:Chrome 计算 图像 加载 Javascript      更新时间:2023-09-26

我在一个页面上有大约四百个图像,我想在图像加载到页面上时向用户显示图像的增量计数器。它在Firefox上运行得很好,但我在IE和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

我还删除了间隔和对updateImagesLoading的调用,只是让countImagesLoading函数也用每个.load函数更新屏幕上的值,但无论我使用哪种方法,我仍然会得到相同的结果:

火狐,它工作。Chrome,它可以工作,但最终距离页面上应该加载的图像的真实数量(464)还差十五到二十个。IE,在所有图像完全加载之前,不会通过$colThree.html('<strong>'+imgCount+'</strong>');显示计数更新,因此它为空,然后显示464。

这里我认为问题是这个脚本在ready事件上执行,但图像在DOM中一找到就开始加载。

如果您可以以某种方式将所有图像的src更改为一个加载图像,并将实际的src放在其他一些属性中,比如data-src,那么问题就应该解决了。然后在就绪事件上,获取每个图片并加载图片,从data-src属性获取url。当它在JS ser中完全加载时,图片的url。

$('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;
});