Johannes
Johannes

Reputation: 177

Javascript image.onload() guarantees image is loaded?

I am working on an HTML5 game which uses a lot of images. However, sometimes the game does not load properly and throws some error messages that suggest that some images have not been loaded correctly. I use a preloading function, incrementing a variable before starting to set the src of an image and decrementing it in the onload() function. Only when this variable reached 0, i start drawing. Still sometimes I (and other users) see errors and the game doesnt load. Most of the time it works though. Now I wonder... technically this should not be possible. Does the call of the onload function guaratee the image is loaded ? Because I feel it doesnt.

Here the code although I dont think it matters:

var ressourcesToLoad = 1;

// all the loadImage() calls
// ...

ressourceLoaded();


function ressourceLoaded()
{
    ressourcesToLoad--;

    // if(ressourcesToLoad == 0) start main loop
}


function loadImage(imgFile)
{
    ressourcesToLoad++;
    var img = new Image();
    img.onload = ressourceLoaded();
    img.src = imgFile;
    return img;
}

Upvotes: 4

Views: 1081

Answers (2)

haldagan
haldagan

Reputation: 911

Yes, BUT as far as I remember:

1 In some browsers it can fire twice in a row for the same image

2 In some browsers it doesn't fire when image is loaded from cache

3 I'm not sure if it fires when server returns 404 for the image

And probably you should start loading next image only after loading previous. If you have a lot of big images on the same domain and start them loading simultaneously, the "two connections per page" rule can break something for you.

P.S.: By some "some browsers" I mean "some browsers or their outdated versions".

Upvotes: 2

Bart
Bart

Reputation: 17361

No the complete property tells you more accurate if the image has finished loading. Unfortunately there is no event that will be triggered when loading is done. One way could be to poll this property until it is set to true.

Upvotes: 0

Related Questions