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.

1
  • 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. Commented Nov 24, 2013 at 12:50

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

3 Comments

@user1690718: because browsers are single-threaded. Synchronous operations are not recommended in browsers as it will block. You should put your code inside callback
@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
@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 stackoverflow.com/questions/9421202/…, stackoverflow.com/questions/1149829/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.