Make sure all images are loaded in `$ (window) .load ()` before proceeding

I am adding a few large images for the slide show to the page, but I want to start loading these images only when the normal part of the page is fully loaded (including images).

To do this, I add images to the function $(window).load():

var slide_total = 20;

$(window).load(function() {

    for (i = 2; i <= slide_total; i++)
    {
        content = '<li><img src="/images/header' + ((i < 10) ? '0' : '') + i + '.jpg" width="960" height="314"></li>';
        $("#slideshow li:last-child").after(content);
    }

    slide_interval = setInterval( "slideSwitch()", slide_duration );

});

The slide show slideSwitch()should begin when all the images are fully loaded, but, as it is now, it starts from the moment elements are added to the DOM.

I cannot move the loop to a function document.ready, because I do not want the slide show to interfere with loading normal images.

How to check if all images are loaded before setting the interval?

+3
1

:

// get the total number of images inserted in the DOM
var imgCount = $('#slideshow img').length;

// initialize a counter which increments whenever an image finishes loading
var loadCounter = 0;

// bind to the images' load event
$("#slideshow li img").load(function() {

    // increment the load counter
    loadCounter++;

    // once the load counter equals the total number of images
    // set off the fancy stuff
    if(loadCounter == imgCount) {
        slide_interval = setInterval( "slideSwitch()", slide_duration );
    }
}).each(function() {

    // trigger the load event in case the image has been cached by the browser
    if(this.complete) $(this).trigger('load');
});
+4

Source: https://habr.com/ru/post/1763826/


All Articles