summaryrefslogtreecommitdiff
path: root/loader.js
blob: 9de5cb32b72f4bed537e291ca8d62dcc164f4b13 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
/*****************************************************

// 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(){
}
******************************************************/

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();
}