3

I'm using a mix of .ready() and .load() to execute my desired function.

jQuery(document).ready(function($) {
    $("img").load(function() {
        // Function goes here
    });
});

As you can see, this waits for the DOM to be ready, then on each <img> load, it executes the code.

If I only had one image to load this would be simple.

But the problem is -- what if I have 10 images to be loaded? The function will be called 10 times due to each image loading one by one, and that's not a very efficient way to go about it just to achieve what I want.

So here's the question -- is there a more efficient way to wait for all images to load, then execute the function once?

7

3 Answers 3

4

You could do something like this to avoid having your function run multiple times.

jQuery(document).ready(function($) {
    var nrOfImages = $("img").length;
    $("img").load(function() {
        if(--nrOfImages == 0)
        {
            // Function goes here
        }
    });
});
1
jQuery(window).load(function() {
    alert("page finished loading now.");
});

jQuery(window).load(...) will be triggered after all content on the page has been loaded. This different from jQuery(document).load(...) which is triggered after the DOM has been loaded. I think this will solve your issue.

0

If anybody wants to know, my final result was this:

(function($) {
    $(window).load(function(){
        // Function goes here
    });
})(jQuery);

that's because

jQuery(window).load(function($) {});

isn't a jQuery object, as referenced in this question:

Calling jQuery on (window).load and passing variable for 'No Conflict' code

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.