/***************************************************** // sample config var config = {}; config.images = []; // sample app function app = {}; app.init = function(){ app.load(); } app.load = function(){ app.loader = new Loader (); app.loader.register("loading"); // register loaders here app.loader.ready("loading"); } app.ready = function(){ } // so basically he also puts a bunch of variables in the global namespace. Does that seem // contradictory to an OOP approach? in global namespace where will be only app variable. no there are also // ******************************************************/ function Loader (readyCallback){ this.assets = {}; this.readyCallback = readyCallback || app.ready; } // Register an asset as loading Loader.prototype.register = function(s){ this.assets[s] = false; } // Signal that an asset has loaded Loader.prototype.ready = function(s){ console.log("ready >> " + s); this.assets[s] = true; if (this.loaded) return; if (! this.isReady()) return; this.loaded = true; this.readyCallback(); } // (boolean) Is the loader ready? Loader.prototype.isReady = function(){ for (var s in this.assets) { if (this.assets.hasOwnProperty(s) && this.assets[s] != true) { return false; } } return true; } // (int) Number of assets remaining Loader.prototype.remainingAssets = function(){ var n = 0; for (var s in this.assets) { if (this.assets.hasOwnProperty(s) && this.assets[s] != true) { n++; console.log('remaining: ' + s); } } return n; } // Preload the images in config.images Loader.prototype.preloadImages = function(){ for (var i = 0; i < config.images.length; i++) { this.preloadImage(config.images[i]); } } Loader.prototype.preloadImage = function(src){ var _this = this; this.register(src); var img = new Image(); img.onload = function(){ _this.ready(src); } img.src = src; if (img.complete) img.onload(); }