views:

217

answers:

2

I want to preload images but ensure they are loaded before continuing. How can I do this?

The following does not work as it sends off the load request only, but doesn't wait till the image is loaded. So it is possible that the image isn't loaded when requested soon after.

jQuery.preloadImages = function () {
        for (var i = 0; i < arguments.length; i++) {
            jQuery("<img>").attr("src", arguments[i]);
        }
    }       
    $.preloadImages("img1.jpg","img2.jpg");
A: 
jQuery.preloadImages = function () {
  var image = new Image();

  for (var i = 0; i < arguments.length; i++) {
      image.src = arguments[i+1];
  }
}

I haven't tested.

TK
that does the same thing - it doesn't load the image immediately.you would use image.onload = function(){...} to use the image when ready, but I need a blocking way of doing it.
Mr. Flibble
+1  A: 

Have you checked this discussion on SO :

http://stackoverflow.com/questions/263359/how-can-i-determine-if-an-image-has-loaded-using-javascript-jquery

Rajat
Thanks. In the end I used the onload handler of the images to keep track of which images are loaded, and the when the counter hits the total number of images I'm good to go.
Mr. Flibble