Image
Screenshot of part 6 of my series Node.js + HTML5 + Socket.io = Game. Code is available  on github. Tutorial coming soon.

Screenshot of part 6 of my series Node.js + HTML5 + Socket.io = Game. Code is available on github. Tutorial coming soon.

Text

Javascript Image Preloader

Browsers offer the ability to provide a callback for when a given image has loaded, but what if you want to run a single callback after multiple images have loaded? The following code does exactly that.

Usage


var loader = new Loader();
var image1 = loader.add('img1.jpg');
var image2 = loader.add('img2.jpg');
loader.onComplete(function () {
    // What to do on complete
});
loader.start();

The class


function Loader() {

	this.images = new Array();
	this.onCompleteCallback = function () { };	
	this.numLoaded = 0;

	this.add = function (path) {
		var loader = this;
		var img = new Image();

		img.onload = function () {
			loader.loaded();
		}

		this.images.push({img: img, path: path});

		return img;
	}

	this.onComplete = function (callback) {
		this.onCompleteCallback = callback;
	}

	this.loaded = function () {
		this.numLoaded++;

		if (this.images.length == this.numLoaded) {
			this.onCompleteCallback();
		}
	}

	this.start = function () {
	    for (var i=0; i<this.images.length; i++)
	        this.images[i].img.src = this.images[i].path;
	}

        return this;
}