0

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?

TMH
  • 6,096
  • 7
  • 51
  • 88

5 Answers5

3

You may try this:

$(window).on('load', function() {
    nowDoTheMainFunction();
});
  • @TomHart, yes they differ, please refer to [this post](http://stackoverflow.com/questions/3698200/window-onload-vs-document-ready) –  Aug 22 '14 at 09:42
  • Just had a read. I'll give this a try now, it's currently in the `.ready()`. – TMH Aug 22 '14 at 09:50
  • This seems to be working for me. I say seem because the issue with my old way was intermittent, and I couldn't force it, so I'll keep my eye on it and report back if this issue is still there. – TMH Aug 22 '14 at 10:25
1

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.

csc
  • 59
  • 2
  • 7
0

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.

Jeremy J Starcher
  • 23,369
  • 6
  • 54
  • 74
0

This must do what you are trying to accomplish

$("#imageDiv img").one('load', function () {
        // Your code
    }).each(function () {
        if (this.complete) $(this).load();
    });
iJade
  • 23,144
  • 56
  • 154
  • 243
0

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');
}
SSA
  • 5,433
  • 4
  • 36
  • 50