aboutsummaryrefslogtreecommitdiffstats
path: root/themes/default/js/image.loader.js
blob: cd8b9cc52430caf943b858c56810c20a50a04d18 (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
function ImageLoader(opts) {
	this.opts = jQuery.extend( {
			maxRequests: 6,
			onChanged: jQuery.noop
		}, opts||{} );
}

ImageLoader.prototype = {
	loaded: 0,
	errors: 0,
	errorEma: 0,

	pause: false,

	current: [],
	queue: [],
	pool: [],

	remaining: function() {
		return this.current.length + this.queue.length;
	},

	add: function(urls) {
		this.queue = this.queue.concat( urls );
		this._fireChanged("add");
		this._checkQueue();
	},

	clear: function() {
		this.queue.length = 0;
		while (this.current.length)
			jQuery( this.current.pop() ).unbind();
		this.loaded = this.errors = this.errorEma = 0;
	},

	pause: function(val) {
		if (val !== undefined)
		{
			this.paused = val;
			this._checkQueue();
		}
		return this.paused;
	},

	_checkQueue: function() {
		while (!this.paused
			&& this.queue.length
			&& this.current.length < this.opts.maxRequests)
		{
			this._processOne( this.queue.shift() );
		}
	},

	_processOne: function(url) {
		var img = this.pool.shift() || new Image;
		this.current.push(img);
		var that = this;
		jQuery(img).bind( "load error abort", function(e) {
		//img.onload = function(e) {
			jQuery(img).unbind();
			img.onload=null;
			that.current.splice(jQuery.inArray(img, that.current), 1);
			if (e.type==="load") {
				that.loaded++;
				that.errorEma *= 0.9;
			}
			else {
				that.errors++;
				that.errorEma++;
				if (that.errorEma>=20 && that.errorEma<21)
					that.paused = true;
			}
			that._fireChanged(e.type, img);
			that._checkQueue();
			that.pool.push(img);
		} );
		img.src = url;
	},

	_fireChanged: function(type, img) {
		this.opts.onChanged(type, img);
	}
}