Preloading Resources using resourceLoader.js

December 14, 2011

Back when i started developing the final project for my book i needed a simple but reliable way to preload assets such as images or sounds. I also intended to show a nice progress bar indicating... well, the progress of the load. I finally settled on developing a somewhat short, simple but efficient class called ResourceLoader that could handle images and sounds but can easily be extended to support other media types, such as videos, or JS scripts.

Using it is pretty simple, too. You just need to do:

var rl = new ResourceLoader(printProgressBar, function() {
    alert('Preloading complete!');

rl.addResource('image.png', null, ResourceType.IMAGE);
rl.addResource('music.mp3', 'audio/mp3', ResourceType.SOUND);


function printProgressBar() {
    var percent = Math.floor((rl.resourcesLoaded * 100) / rl.resources.length);
    // Use the percent variable somewhere in your game/app.

The complete code for resourceLoader.js is available on GitHub