forked from lsblakk/browser-pairs
-
Notifications
You must be signed in to change notification settings - Fork 16
/
pxloader.js
473 lines (402 loc) · 14 KB
/
pxloader.js
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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
/**
* PixelLab Resource Loader
* Loads resources while providing progress updates.
*/
function PxLoader(settings) {
// merge settings with defaults
settings = settings || {};
// how frequently we poll resources for progress
if (settings.statusInterval == null) {
settings.statusInterval = 5000; // every 5 seconds by default
}
// delay before logging since last progress change
if (settings.loggingDelay == null) {
settings.loggingDelay = 20 * 1000; // log stragglers after 20 secs
}
// stop waiting if no progress has been made in the moving time window
if (settings.noProgressTimeout == null) {
settings.noProgressTimeout = Infinity; // do not stop waiting by default
}
var entries = [], // holds resources to be loaded with their status
progressListeners = [],
timeStarted,
progressChanged = +new Date;
/**
* The status of a resource
* @enum {number}
*/
var ResourceState = {
QUEUED: 0,
WAITING: 1,
LOADED: 2,
ERROR: 3,
TIMEOUT: 4
};
// places non-array values into an array.
var ensureArray = function(val) {
if (val == null) {
return [];
}
if (Array.isArray(val)) {
return val;
}
return [ val ];
};
// add an entry to the list of resources to be loaded
this.add = function(resource) {
// ensure tags are in an array
resource.tags = ensureArray(resource.tags);
// ensure priority is set
if (resource.priority == null) {
resource.priority = Infinity;
}
entries.push({
resource: resource,
state: ResourceState.QUEUED
});
};
this.addProgressListener = function(callback, tags) {
progressListeners.push({
callback: callback,
tags: ensureArray(tags)
});
};
this.addCompletionListener = function(callback, tags) {
progressListeners.push({
tags: ensureArray(tags),
callback: function(e) {
if (e.completedCount === e.totalCount) {
callback();
}
}
});
};
// creates a comparison function for resources
var getResourceSort = function(orderedTags) {
// helper to get the top tag's order for a resource
orderedTags = ensureArray(orderedTags);
var getTagOrder = function(entry) {
var resource = entry.resource,
bestIndex = Infinity;
for (var i = 0, len = resource.tags.length; i < len; i++) {
var index = orderedTags.indexOf(resource.tags[i]);
if (index >= 0 && index < bestIndex) {
bestIndex = index;
}
}
return bestIndex;
};
return function(a, b) {
// check tag order first
var aOrder = getTagOrder(a),
bOrder = getTagOrder(b);
if (aOrder < bOrder) return -1;
if (aOrder > bOrder) return 1;
// now check priority
if (a.priority < b.priority) return -1;
if (a.priority > b.priority) return 1;
return 0;
}
};
this.start = function(orderedTags) {
timeStarted = +new Date;
// first order the resources
var compareResources = getResourceSort(orderedTags);
entries.sort(compareResources);
// trigger requests for each resource
for (var i = 0, len = entries.length; i < len; i++) {
var entry = entries[i];
entry.status = ResourceState.WAITING;
entry.resource.start(this);
}
// do an initial status check soon since items may be loaded from the cache
setTimeout(statusCheck, 100);
};
var statusCheck = function() {
var checkAgain = false,
noProgressTime = (+new Date) - progressChanged,
timedOut = (noProgressTime >= settings.noProgressTimeout),
shouldLog = (noProgressTime >= settings.loggingDelay);
for (var i = 0, len = entries.length; i < len; i++) {
var entry = entries[i];
if (entry.status !== ResourceState.WAITING) {
continue;
}
// see if the resource has loaded
entry.resource.checkStatus();
// if still waiting, mark as timed out or make sure we check again
if (entry.status === ResourceState.WAITING) {
if (timedOut) {
entry.resource.onTimeout();
}
else {
checkAgain = true;
}
}
}
// log any resources that are still pending
if (shouldLog && checkAgain) {
log();
}
if (checkAgain) {
setTimeout(statusCheck, settings.statusInterval);
}
};
this.isBusy = function() {
for (var i = 0, len = entries.length; i < len; i++) {
if (entries[i].status === ResourceState.QUEUED ||
entries[i].status === ResourceState.WAITING) {
return true;
}
}
return false;
};
// helper which returns true if two arrays share at least one item
var arraysIntersect = function(a, b) {
for (var i = 0, len = a.length; i < len; i++) {
if (b.indexOf(a[i]) >= 0) {
return true;
}
}
return false;
};
var onProgress = function(resource, statusType) {
// find the entry for the resource
var entry = null;
for(var i=0, len = entries.length; i < len; i++) {
if (entries[i].resource === resource) {
entry = entries[i];
break;
}
}
// we have already updated the status of the resource
if (entry == null || entry.status !== ResourceState.WAITING) {
return;
}
entry.status = statusType;
progressChanged = +new Date;
var numResourceTags = resource.tags.length;
// fire callbacks for interested listeners
for (var i = 0, numListeners = progressListeners.length; i < numListeners; i++) {
var listener = progressListeners[i],
shouldCall;
if (listener.tags.length === 0) {
// no tags specified so always tell the listener
shouldCall = true;
}
else {
// listener only wants to hear about certain tags
shouldCall = arraysIntersect(resource.tags, listener.tags);
}
if (shouldCall) {
sendProgress(entry, listener);
}
}
};
this.onLoad = function(resource) {
onProgress(resource, ResourceState.LOADED);
};
this.onError = function(resource) {
onProgress(resource, ResourceState.ERROR);
};
this.onTimeout = function(resource) {
onProgress(resource, ResourceState.TIMEOUT);
};
// sends a progress report to a listener
var sendProgress = function(updatedEntry, listener) {
// find stats for all the resources the caller is interested in
var completed = 0,
total = 0;
for (var i = 0, len = entries.length; i < len; i++) {
var entry = entries[i],
includeResource;
if (listener.tags.length === 0) {
// no tags specified so always tell the listener
includeResource = true;
}
else {
includeResource = arraysIntersect(entry.resource.tags, listener.tags);
}
if (includeResource) {
total++;
if (entry.status === ResourceState.LOADED ||
entry.status === ResourceState.ERROR ||
entry.status === ResourceState.TIMEOUT) {
completed++;
}
}
}
listener.callback({
// info about the resource that changed
resource: updatedEntry.resource,
// should we expose StatusType instead?
loaded: (updatedEntry.status === ResourceState.LOADED),
error: (updatedEntry.status === ResourceState.ERROR),
timeout: (updatedEntry.status === ResourceState.TIMEOUT),
// updated stats for all resources
completedCount: completed,
totalCount: total
});
};
// prints the status of each resource to the console
var log = this.log = function(showAll) {
if (!window.console) {
return;
}
var elapsedSeconds = Math.round((+new Date - timeStarted) / 1000);
window.console.log('PxLoader elapsed: ' + elapsedSeconds + ' sec');
for (var i = 0, len = entries.length; i < len; i++) {
var entry = entries[i];
if (!showAll && entry.status !== ResourceState.WAITING) {
continue;
}
var message = 'PxLoader: #' + i + ' ' + entry.resource.getName();
switch(entry.status) {
case ResourceState.QUEUED:
message += ' (Not Started)';
break;
case ResourceState.WAITING:
message += ' (Waiting)';
break;
case ResourceState.LOADED:
message += ' (Loaded)';
break;
case ResourceState.ERROR:
message += ' (Error)';
break;
case ResourceState.TIMEOUT:
message += ' (Timeout)';
break;
}
if (entry.resource.tags.length > 0) {
message += ' Tags: [' + entry.resource.tags.join(',') + ']';
}
window.console.log(message);
}
};
}
// shims to ensure we have newer Array utility methods
// https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/isArray
if (!Array.isArray) {
Array.isArray = function(arg) {
return Object.prototype.toString.call(arg) == '[object Array]';
};
}
// https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/indexOf
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function(searchElement /*, fromIndex */) {
"use strict";
if (this == null) {
throw new TypeError();
}
var t = Object(this);
var len = t.length >>> 0;
if (len === 0) {
return -1;
}
var n = 0;
if (arguments.length > 0) {
n = Number(arguments[1]);
if (n != n) { // shortcut for verifying if it's NaN
n = 0;
} else if (n != 0 && n != Infinity && n != -Infinity) {
n = (n > 0 || -1) * Math.floor(Math.abs(n));
}
}
if (n >= len) {
return -1;
}
var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
for (; k < len; k++) {
if (k in t && t[k] === searchElement) {
return k;
}
}
return -1;
};
}
/**
* PxLoader plugin to load images
*/
function PxLoaderImage(url, tags, priority) {
var self = this,
loader = null;
this.img = new Image();
this.tags = tags;
this.priority = priority;
var onReadyStateChange = function () {
if (self.img.readyState == 'complete') {
removeEventHandlers();
loader.onLoad(self);
}
};
var onLoad = function() {
removeEventHandlers();
loader.onLoad(self);
};
var onError = function() {
removeEventHandlers();
loader.onError(self);
};
var removeEventHandlers = function() {
self.unbind('load', onLoad);
self.unbind('readystatechange', onReadyStateChange);
self.unbind('error', onError);
};
this.start = function(pxLoader) {
// we need the loader ref so we can notify upon completion
loader = pxLoader;
// NOTE: Must add event listeners before the src is set. We
// also need to use the readystatechange because sometimes
// load doesn't fire when an image is in the cache.
self.bind('load', onLoad);
self.bind('readystatechange', onReadyStateChange);
self.bind('error', onError);
self.img.src = url;
};
// called by PxLoader to check status of image (fallback in case
// the event listeners are not triggered).
this.checkStatus = function() {
if (self.img.complete) {
removeEventHandlers();
loader.onLoad(self);
}
};
// called by PxLoader when it is no longer waiting
this.onTimeout = function() {
removeEventHandlers();
if (self.img.complete) {
loader.onLoad(self);
}
else {
loader.onTimeout(self);
}
};
// returns a name for the resource that can be used in logging
this.getName = function() {
return url;
};
// cross-browser event binding
this.bind = function(eventName, eventHandler) {
if (self.img.addEventListener) {
self.img.addEventListener(eventName, eventHandler, false);
} else if (self.img.attachEvent) {
self.img.attachEvent('on'+eventName, eventHandler);
}
};
// cross-browser event un-binding
this.unbind = function(eventName, eventHandler) {
if (self.img.removeEventListener) {
self.img.removeEventListener(eventName, eventHandler, false);
} else if (self.img.detachEvent) {
self.img.detachEvent('on'+eventName, eventHandler);
}
};
}
// add a convenience method to PxLoader for adding an image
PxLoader.prototype.addImage = function(url, tags, priority) {
var imageLoader = new PxLoaderImage(url, tags, priority);
this.add(imageLoader);
// return the img element to the caller
return imageLoader.img;
};