Cod*_*oso 4 javascript jquery image image-loading
我有一个页面,其中包含十几个大图像:
<div id="gallery">
  <img src="1.png" alt="" />
  <img src="2.png" alt="" />
  ...
</div>
由于图像的大小,并行下载会在任何显示之前导致太长的延迟.
问题:如何按顺序加载图像,以便2.png仅1.png在完全加载和显示后才开始加载?
我不想延迟加载(除非你知道一个插件,它总是严格按照相同的顺序加载图像,不管当前的视口)
此解决方案:在最新的Chrome,Firefox,IE中,按顺序加载图像对我不起作用.它将立即加载所有图像,然后显示它们
在这个答案中建议的插件/sf/answers/1804203341/有点功能,但它一次发出2,3或更多的请求,所以不做它应该做的事情
然后是这个插件,也在一些答案中提出:http://imagesloaded.desandro.com/ 它的意思是其他东西 - 让你知道什么时候加载所有图像,它做得很好.所以我试着像这样使用它:
var $ gallery = $("#gallery"); 
  $ gallery.imagesLoaded(function(){$ gallery.append(''); console.log("Image loaded");}); $ gallery.append( '');
这里的想法是 - 在imagesLoaded事件上逐个动态添加图像.但是,它仅针对第一个图像触发(尽管它也是动态添加的),而第二个图像则不会触发.因此上面的代码会导致两个图像显示,但只有1个console.log()通知
任何建议赞赏.
基本上你想从一个空容器开始.图像的路径将包含在Javascript数组中,然后使用屏幕外元素加载方法一个接一个地引入.码:
<div id="gallery"></div>
<script>
var images = [
    { src: '1.png', alt: 'I am the first image' },
    { src: '2.png', alt: 'Second image' }
];
function loadImageSequentially(imagesArray, appendTo, loadImageAtIndex) {
    if (!loadImageAtIndex) loadImageAtIndex = 0; // assume first loading if not provided.
    if (!imagesArray[loadImageAtIndex]) return;
    var img = new Image();
    // attach listeners first
    img.onload = function() {
        appendTo.appendChild(img);
        loadImageSequentially(imagesArray, appendTo, loadImageAtIndex + 1);
    }
    img.onerror = function() {
        // remove the onload listener
        img.onload = null;
        img.src = 'error.png';
        // life goes on...
        appendTo.appendChild(img); 
        loadImageSequentially(imagesArray, appendTo, loadImageAtIndex + 1);     
    }
    // assign attributes, which will start the loading.
    img.src = imagesArray[loadImageAtIndex].src;
    img.alt = imagesArray[loadImageAtIndex].alt;
}
// now run it.
var appendTo = document.getElementById('gallery')
loadImageSequentially(images, appendTo);
</script>
这个例子可以模块化并且更好.但是为了说明的目的留下来.