Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I sync up multiple image onload calls?

I want a function to run when specific images are loaded, but I don't know how to wait for both to load before running. I only know how to chain them, like below:

Image1 = new Image();
Image1.src = 'image1-link.jpg';

Image2 = new Image();
Image2.src = 'image2-link.jpg';

Image1.onload = function() {
    Image2.onload = function() { ... }
}

The downside to this is it has to wait till Image1 completely loads before getting the second. I want to try something like this:

Image1 = new Image();
Image1.src = 'image1-link.jpg';

Image2 = new Image();
Image2.src = 'image2-link.jpg';

(Image1 && Image2).onload = function() { ... }

EDIT: Thank you both for the help Paul Grime and ziesemer. Both your answers are very good. I think I have to give the best answer to Paul Grime, although his uses more code, I only need to know the src of the images and the onload function is built in while in ziesemer's answer I need to know both the src, the count of the images, and have to write multiple onload lines.

Depending on the situation, both have their purpose. Thank you both for the help.

like image 845
Ark-of-Ice Avatar asked Dec 30 '11 17:12

Ark-of-Ice


People also ask

Which method is used to load image synchronously?

To make an image load synchronously with JavaScript, we can make a promise that loads the image. We define the loadImage functino that returns a promise with the img element. We create the img element with the Image constructor.

Is onload synchronous?

The behaviour of the OnLoad event is synchronous i.e., when you run an asynchronous code on load of a form and want to hide some fields based on the code response, the form will be loaded first with all the fields including the field you wanted to hide on load of the form.

How does image onload work?

The onload event occurs when an object has been loaded. onload is most often used within the <body> element to execute a script once a web page has completely loaded all content (including images, script files, CSS files, etc.).

How does onload work JavaScript?

The onload property processes load events after the element has finished loading. This is used with the window element to execute a script after the webpage has completely loaded. The function that is required to be executed is assigned as the handler function to this property.


2 Answers

This fiddle might help. It's a simple generic 'loader'.

http://jsfiddle.net/8baGb/1/

And the code:

// loader will 'load' items by calling thingToDo for each item,
// before calling allDone when all the things to do have been done.
function loader(items, thingToDo, allDone) {
    if (!items) {
        // nothing to do.
        return;
    }

    if ("undefined" === items.length) {
        // convert single item to array.
        items = [items];
    }

    var count = items.length;

    // this callback counts down the things to do.
    var thingToDoCompleted = function (items, i) {
        count--;
        if (0 == count) {
            allDone(items);
        }
    };

    for (var i = 0; i < items.length; i++) {
        // 'do' each thing, and await callback.
        thingToDo(items, i, thingToDoCompleted);
    }
}

function loadImage(items, i, onComplete) {
    var onLoad = function (e) {
        e.target.removeEventListener("load", onLoad);

        // this next line can be removed.
        // only here to prove the image was loaded.
        document.body.appendChild(e.target);

        // notify that we're done.
        onComplete(items, i);
    }
    var img = new Image();
    img.addEventListener("load", onLoad, false);
    img.src = items[i];
}

var items = ['http://bits.wikimedia.org/images/wikimedia-button.png',
             'http://bits.wikimedia.org/skins-1.18/common/images/poweredby_mediawiki_88x31.png',
             'http://upload.wikimedia.org/wikipedia/en/thumb/4/4a/Commons-logo.svg/30px-Commons-logo.svg.png',
             'http://upload.wikimedia.org/wikipedia/commons/3/38/Icons_example.png'];

loader(items, loadImage, function () {
    alert("done");
});
like image 176
Paul Grime Avatar answered Sep 22 '22 12:09

Paul Grime


If you can't use something like jQuery, create a helper function that you can pass to the onload of all your images you are interested in. Each time it is called, increment a counter, or add the src name to a set. Once the counter or your set reaches the size of all of the images that you are expecting, then you can fire off whatever work you really wanted to do.

Something like:

var imageCollector = function(expectedCount, completeFn){
  var receivedCount;
  return function(){
    if(++receivedCount == expectedCount){
      completeFn();
    }
  };
}();

var ic = imageCollector(2, function(){alert("Done!");});
Image1.onload = ic;
Image2.onload = ic;
like image 41
ziesemer Avatar answered Sep 21 '22 12:09

ziesemer