CodeVirtuoso
CodeVirtuoso

Reputation: 6438

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

I have a page which contains a dozen of big images:

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

Due to images' size, parallel downloading causes too long delay before anything shows.

Question: how to load images sequentially, so that 2.png only starts loading after 1.png has been fully loaded and displayed?

The idea here was - to dynamically add images one by one, on imagesLoaded event. However, it gets triggered only for the first image (although it's dynamically added as well), and for the second it doesn't. So the above code causes both images to show, but only 1 console.log() notification

Any suggestions appreciated.

Upvotes: 4

Views: 1252

Answers (2)

Calvintwr
Calvintwr

Reputation: 8798

Basically you want to start with an empty container. The path to the images would be contained in a Javascript array, and then brought in one after another using a off-screen element loading methodology. Code:

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

This example can be modularised and made better. But is left at such for the purpose of illustration.

Upvotes: 7

Luke P. Issac
Luke P. Issac

Reputation: 1591

Try using lazy load on page scroll. It starts loading of images when user scrolls to that, so images are not loaded parallelly, instead it will be sequential ine after other in a way.

Upvotes: 0

Related Questions