Question

I am currently developing a HTML/Javascript game which requires the use of images. The user has a certain amount of time to answer the question. What I am asking is what is the best way to download and cache files and make sure they are ready? Is it AppCache I am looking for?

Was it helpful?

Solution

You need to delay the execution of your game loop until all the required assets are loaded. Hopefully your code is already modular enough to allow for this.

The browser fires an event when the resource located at the src of an image element has been downloaded. Using this event, you can create a basic preloading solution:

var img = new Image();

img.onload = function() {                             
    console.log('Image loaded!');
};

img.src = '/images/my-image.jpg';

Expand this solution to iterate over all your assets. Once they're loaded, call the code that begins your game loop.

There are a number of prebuilt solutions available:

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top