views:

44

answers:

3

Hi,

I'm writing an image pre-loader for my html5 project and I've struck a problem. Images that are used in the game are defined with the image object within JavaScript like so:

images = new Array();
images[0] = new Image();
images[0].src = '/images/tiles/grass.png';

As soon as "document.ready" the pre-loader function as seen below is run.

function preLoader(){
    while(loaded != images.length){
        var loaded = 0;
        for(var loadTest = 0; loadTest < images.length; loadTest++){
            if(images[loadTest].complete){
                loaded ++;
            }
        }
        console.log(loaded);
    }
    console.log("loaded all");
}

The problem is that the loop never ends because images[loadTest].complete always returns false. I've tested running the function a few seconds after the page loads when the image has defiantly loaded and it works just fine.

Due to this I'm assuming that the while loop running is stopping the images from loading. If that is true how would I go about fixing this problem?

+1  A: 

The handler passed to .ready() is guaranteed to be executed after the DOM is constructed, but before assets such as images are received.

You may want to use the .load() handler instead:

$(window).load(function () {
  // run code when the page is fully loaded including graphics.
});

This is assuming you are using jQuery.

Daniel Vassallo
+2  A: 

Alternatively to an onload event you can load images or do polling via a setTimeout or setInterval call. This causes the code to run in a non-blocking fashion.

setInterval('checkimages()', 1000)
SpliFF
+1  A: 

You have some errors in your code.

  • The big problem is that you are doing polling in a loop, which you shouldn't do in Javascript. Javascript is run in the same thread as the page, so processing in Javascript blocks other things in the page including loading and user interaction. It's also a bad idea in general to do polling without some kind of delay during which you relinquish control of the CPU.

    Polling should be done using setInterval() or setTimeout() rather than a loop.

  • Another problem is during your loop, your loaded variable is incremented any time one or more images has loaded each time the loop runs, so that loaded is likely to reach images.length not when all images have loaded but when at least one has loaded.

thomasrutter