0

i'm trying to check if all images are loaded within a container using the below code

$(document).ready(function () {
    $(".slide img").each(function (index) {
        var fakeSrc = $(this).attr('src');
        $("<img/>").attr("src", fakeSrc).css('display', 'none').load(function () {
            alert('loaded');
        }).
        error(function () {
            load_img_Single(fakeSrc);
        });
    });
    function load_img_Single(img) {
        alert(img);
        var ruth;
        $("<img/>").attr("src", img).css('display', 'none').load(function () {
            ruth = 'yeap';
        }).error(function () {
            ruth = 'nope';
        });
        alert(ruth);
    }
});

now as u can see im using a fake container to load the image and check if it has been loaded or not .

im using the .error in the first check of image to see if it was loaded properly or not , if not it executes the function load_img_Single(image) function of mine to load it again.

now in that function again im checking if it was loaded or not . but the problem is the variable 'ruth' is not getting set to anything within that function. its been declared outside but still its coming as 'undefined'.

any insight would be appreciated guys.

Tushar Gupta - curioustushar
  • 58,085
  • 24
  • 103
  • 107
mega-crazy
  • 838
  • 2
  • 17
  • 36
  • Loading an image is asynchronous, it does not block the browser, so the code continues execution and the callback is called once the image is loaded, and when you check your variable the callback hasn't executed yet. – adeneo Nov 24 '13 at 12:50

1 Answers1

1

The reason is loading image is asynch. When you call:

$("<img/>").attr("src", img).css('display', 'none').load(function() {
        ruth = 'yeap';
    }).error(function() { ruth = 'nope'; });

The load or error do not fire yet. That's why ruth is undefined when you call alert(ruth); right after that

Khanh TO
  • 48,509
  • 13
  • 99
  • 115
  • @user1690718: because browsers are single-threaded. Synchronous operations are not recommended in browsers as it will block. You should put your code inside callback – Khanh TO Nov 24 '13 at 12:59
  • @user1690718 .load(callback), in fact .on('load',callback) is an event, event cannot be 'sync', that's a non sense as event get fired reacting to something happening. Here once image get loaded. You can manually trigger event (handler) but this is not what you are looking for here – A. Wolff Nov 24 '13 at 13:03
  • @user1690718: workarounds are always not good and not recommended. Asynchrony is browser's nature, we should not go against it. If you still need a workaround, you could take at look at some discussions like preloading images http://stackoverflow.com/questions/9421202/how-do-i-make-an-image-load-synchronously, http://stackoverflow.com/questions/1149829/loading-images-synchronously-with-javascript – Khanh TO Nov 24 '13 at 13:16