Search code examples
javascriptjqueryloadingcreatejs

Preload all sound and images before starting animation


I'm building a simple animation web app that involves sound and images. I want it so that when a user enters the site they see a "now loading" page, and when all the images and audio files are done loading it calls a function that starts the animation. So far the code I have is roughly this:

var img1, img2;
var sound1, sound2;

function loadImages() {
    img1=new Image();
    img1.src="...";
    img2=new Image();
    img2.src="...";
    img1.onload=img2.onload=handleImageLoad;
}

function loadSound() {
    createjs.Sound.registerSound({id:"sound1", src:"sound1.wav"});
    createjs.Sound.registerSound({id:"sound2", src:"sound2.wav"}); 
    createjs.Sound.addEventListener("fileload", handleSoundLoad);
}

function handleImageLoad(e) {
    //Do something when an image loads
}

function handleSoundLoad(e) {
    //Do something when a sound loads
    if(e.id=="sound1") sound1 = createjs.Sound.createInstance("sound1");
    else if(e.id=="sound2") sound2 = createjs.Sound.createInstance("sound2");
}

$(document).ready(function() {
    //overlay a "now loading" .gif on my canvas
    ...
    ...

    loadSound(); 
    loadImages();
}

// call this when everything loads
function start() {
    //remove "now loading..." overlay .gif
    ...
    ...

    //start animating
}

handleImageLoad() and handleSoundLoad() are invoked independently of each other so I can't rely on them on calling start(). How can I figure out when everything is loaded? What callback function(s) can I use to achieve this?


Solution

  • Using the built-in SoundJS registerSound method is not bad, but PreloadJS will handle both Sounds and images (and other types) in a single queue. Check out the examples in the PreloadJS GitHub.

    http://preloadjs.com and http://github.com/CreateJS/PreloadJS/