简体   繁体   中英

Run a function once every image in a div has loaded

Say I have this markup

<div id="imageDiv">
    <img src="/img/1.jpg" />
    <img src="/img/2.jpg" />
    <img src="/img/3.jpg" />
    <img src="/img/4.jpg" />
    <img src="/img/5.jpg" />
</div>

What I want to do is run a function, but only after all the images have loaded in. Now, I haven't any actual code to show, but the only way I can see to do this is this (psuedo-code, so untested)

function imagesReady(){
    $.each(imageReady, function(key, val){
        if (!val){
            return;
        }
    });
    nowDoTheMainFunction();
}
var imageReady = [];
$.each(imageDiv, function(key,imageElement){
    imageReady[key] = false;
    imageElement.addLoadListener(function(){
        imageReady[key] = true;
        imagesReady();
    });
});

Is there a neater/better way than that to do this?

You may try this:

$(window).on('load', function() {
    nowDoTheMainFunction();
});

The best way I think to be able to do this is do use JQuery onload function .

$( "#imageDiv" ).load(function() {
    // once the images have loaded
});

This will wait until images have loaded before any of the function is able to run.

The easiest way is to use the window.onload event. This won't fire until all of the resources, including CSS and Images, have loaded and are ready.

This must do what you are trying to accomplish

$("#imageDiv img").one('load', function () {
        // Your code
    }).each(function () {
        if (this.complete) $(this).load();
    });

This might not be the thing you are looking for but out of curiosity, I made something. May be it will help you.

Demo

HTML:

<div id="imageDiv"></div>

Js:

var sources = ['http://i.imgur.com/qNRcqpo.jpg?1', 'http://i.imgur.com/iXTvWhX.jpg']  ;
var images = {};
    var loadedImages = 0;
    var numImages = sources.length;


    for (var src in sources) {
        images[src] = document.createElement("img");;
        images[src].id = src;
        images[src].onload = function () {

            if (++loadedImages >= numImages) {
                functionTobeCalled();
            }

        };
        images[src].src = sources[src];
         $('#imageDiv').append(images[src]);
    }

function functionTobeCalled (){
alert('all images loaded');
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM