Jake
Jake

Reputation: 11430

How to get jQuery to wait for a list of images to load before processing them?

How to tell jQuery to wait for a list of images to be loaded before starting an image carousel?

I have a list of large images that are to be used in an image carousel. These images are of different sizes and I want to use javascript/jQuery to size the viewport according to the widest image and at the same time scale all images to the same height.

<div id="viewport" style="overflow:hidden" class="clearfix">
    <ul id="carousel" style="width:2000em">
       <li><img src="large01.jpg"></li>
       <li><img src="large02.jpg"></li>
       <li><img src="large03.jpg"></li>
       <li><img src="large04.jpg"></li>
       <li><img src="large05.jpg"></li>
       <!-- li { float: left } -->
    </ul>
</div>

I think I need to wait for all the images to load before I can determine their $(img).height() and $(img).width() but I have tried $(document).ready(), $(window).load(), $(window).ready() with inconsistent results across browsers. Furthermore, it seems that some .load() is deprecated already.

What is the correct method of dealing with this.

Or is there anyway to get the image width and height BEFORE the image is loaded?

Upvotes: 1

Views: 578

Answers (2)

Olim Saidov
Olim Saidov

Reputation: 2844

This should do the job:

var images = $('#carousel img');
var count = images.length;
var loaded = 0;

images.each(function() {
    var image = new Image();
    image.onload = function() {
        loaded += 1;

        if (loaded == count) {
            //all images loaded
        }
    }

    image.src = $(this).attr('src');
});

Upvotes: 1

mateuscpf
mateuscpf

Reputation: 95

According to jQuery documentation (see jQuery .ready() Documentation), the correct way of waiting a page to load is '$( document ).ready( handler )'. But to your question I would check the javascript naturalHeight property of the images (or naturalWidth if you will). I believe it's already set when the page is loaded (as per .ready function). You should get the values you need to be able to scale your images.

Upvotes: 0

Related Questions