Line | |
---|
1 | |
---|
2 | function ImageLoader(opts) { |
---|
3 | this.opts = jQuery.extend( { |
---|
4 | maxRequests: 6, |
---|
5 | onChanged: jQuery.noop |
---|
6 | }, opts||{} ); |
---|
7 | } |
---|
8 | |
---|
9 | ImageLoader.prototype = { |
---|
10 | loaded: 0, |
---|
11 | errors: 0, |
---|
12 | errorEma: 0, |
---|
13 | |
---|
14 | pause: false, |
---|
15 | |
---|
16 | current: [], |
---|
17 | queue: [], |
---|
18 | pool: [], |
---|
19 | |
---|
20 | remaining: function() { |
---|
21 | return this.current.length + this.queue.length; |
---|
22 | }, |
---|
23 | |
---|
24 | add: function(urls) { |
---|
25 | this.queue = this.queue.concat( urls ); |
---|
26 | this._fireChanged("add"); |
---|
27 | this._checkQueue(); |
---|
28 | }, |
---|
29 | |
---|
30 | clear: function() { |
---|
31 | this.queue.length = 0; |
---|
32 | while (this.current.length) |
---|
33 | jQuery( this.current.pop() ).unbind(); |
---|
34 | this.loaded = this.errors = this.errorEma = 0; |
---|
35 | }, |
---|
36 | |
---|
37 | pause: function(val) { |
---|
38 | if (val !== undefined) |
---|
39 | { |
---|
40 | this.paused = val; |
---|
41 | this._checkQueue(); |
---|
42 | } |
---|
43 | return this.paused; |
---|
44 | }, |
---|
45 | |
---|
46 | _checkQueue: function() { |
---|
47 | while (!this.paused |
---|
48 | && this.queue.length |
---|
49 | && this.current.length < this.opts.maxRequests) |
---|
50 | { |
---|
51 | this._processOne( this.queue.shift() ); |
---|
52 | } |
---|
53 | }, |
---|
54 | |
---|
55 | _processOne: function(url) { |
---|
56 | var img = this.pool.shift() || new Image; |
---|
57 | this.current.push(img); |
---|
58 | var that = this; |
---|
59 | jQuery(img).bind( "load error abort", function(e) { |
---|
60 | //img.onload = function(e) { |
---|
61 | jQuery(img).unbind(); |
---|
62 | img.onload=null; |
---|
63 | that.current.splice(jQuery.inArray(img, that.current), 1); |
---|
64 | if (e.type==="load") { |
---|
65 | that.loaded++; |
---|
66 | that.errorEma *= 0.9; |
---|
67 | } |
---|
68 | else { |
---|
69 | that.errors++; |
---|
70 | that.errorEma++; |
---|
71 | if (that.errorEma>=20 && that.errorEma<21) |
---|
72 | that.paused = true; |
---|
73 | } |
---|
74 | that._fireChanged(e.type, img); |
---|
75 | that._checkQueue(); |
---|
76 | that.pool.push(img); |
---|
77 | } ); |
---|
78 | img.src = url; |
---|
79 | }, |
---|
80 | |
---|
81 | _fireChanged: function(type, img) { |
---|
82 | this.opts.onChanged(type, img); |
---|
83 | } |
---|
84 | } |
---|
Note: See
TracBrowser
for help on using the repository browser.