有没有办法(JavaScript或jQuery)顺序加载图片(防止并行下载)

Is there a way (JavaScript or jQuery) to sequentially load images (prevent parallel downloads)

我有一个包含十几个大图片的页面:

<div id="gallery">
  <img src="1.png" alt="" />
  <img src="2.png" alt="" />
  ...
</div>

由于图像的大小,并行下载会在显示任何内容之前造成过长的延迟。

问题:如何顺序加载图片,使得2.png只有在1.png加载完毕显示后才开始加载?

这里的想法是 - 在 imagesLoaded 事件中动态地一张一张地添加图像。但是,它仅针对第一张图像被触发(尽管它也是动态添加的),而第二张则不会。所以上面的代码导致两个图像都显示,但只有 1 console.log() notification

感谢任何建议。

基本上你想从一个空容器开始。图像的路径将包含在 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 listeners
        img.onload = img.onerror = null;
        img.src = 'error.png'; // if you have a placeholder error png to display, put it here.

        // 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>

这个例子可以模块化并变得更好。但是为了说明的目的留在这里。

尝试在页面滚动时使用延迟加载。它会在用户滚动到该位置时开始加载图像,因此图像不会并行加载,而是会以某种方式依次加载。