Images don't load while javascript while loop runs
I'm writing an image pre-loader for my html5 project and I've struck a problem. Images t开发者_Python百科hat 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?
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)
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.
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 thatloaded
is likely to reachimages.length
not when all images have loaded but when at least one has loaded.
You can use the Image.onload event. I'm not very good with Javascript, but something like this should work and avoids using timers:
var loadCounter = 0;
function imageLoaded() {
loadCounter++;
if(loadCounter == images.length) {
console.log("images loaded");
}
}
images = new Array();
images[0] = new Image();
images[0].onload = imageLoaded;
images[0].src = '/images/tiles/grass.png';
Basically, whenever an image is loaded, we increment the counter. If all images have been loaded, we log the output.
精彩评论