5

I am using javascript to preload several images with the following code:

// do the following for each image where 'this' is the path
(new Image()).src = this;

This works fine - in firebug I can see each image download being fired off after each iteration.

My problem is that I want to block until the actual download is complete. In other words, I want to show a "image downloading" dialog to the user until all the images have finished downloading.

Right now if I simply show the dialog before the preload loop is executed (and remove the dialog after the loop is completed) it simply captures the download requests NOT the actual download completes.

Since it seems that the actual downloading is asynchronous, is there any way to block until all the downloads have completed?

lok
  • 85
  • 1
  • 3

3 Answers3

2
$(function () {
    var imgs = $('img');
    var length = imgs.length;
    var loaded = 0;
    $('img').hide().each(function () {
        $(this).bind('load', function () {
            if ((++loaded) === length) {
                imgs.show();
            }else { 
              //show images are still downloading
            }
        });
    });
});
  • There's no need for a `.each()` when binding :) – Nick Craver Dec 13 '10 at 15:19
  • @nick can u explain it a bit more, I'm interested in learning it.. I haven't worked with jQuery for the past 3 weeks :) –  Dec 13 '10 at 15:24
  • 1
    `.bind()` works on all elements in the set, and there's also a shortcut for most events, like `.load()`, so above you would narrow it down to this: http://www.jsfiddle.net/nick_craver/Uu2jz/ ...note this assumed the `.src` is set later and the images haven't already loaded, if that's the case you need to loop through and check `.complete`, firing the `load` event on those that have. – Nick Craver Dec 13 '10 at 15:27
0

You can hide the div that has the content you are preloading your images for while showing the "loading" div until the preload is complete. It would look something like this:

$('#content').hide();
$('#loading').show();

// for loop loading images here

$('#loading').hide();
$('#content').show();
ryanulit
  • 4,983
  • 6
  • 42
  • 66
  • thanks but I dont think you understood my question. the loop which loads the images only triggers the download - it doesn't block until its complete. – lok Dec 13 '10 at 15:09
0

You can use the onload method which is fired when image is successfully downloaded, then set your next step in the onload function.

Here's the W3 school's reference:

http://www.w3schools.com/jsref/event_img_onload.asp

tshao
  • 1,127
  • 2
  • 8
  • 23