-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathjquery.haymaker.js
More file actions
124 lines (98 loc) · 2.52 KB
/
jquery.haymaker.js
File metadata and controls
124 lines (98 loc) · 2.52 KB
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
/**
* A preloader of images/ajax requests.
* Uses sessionStorage to try and not "cache" the same image twice.
* Releases UI thread every 300ms.
*
* Example:
* var hm = new $.HayMaker();
* hm.queue(['an_image.jpg', '/some/service', 'another_image.png']);
*
* @author Brendan Barr - brendanbarr.web@gmail.com
*/
(function($) {
if (typeof $.HayMaker !== 'undefined') {
throw new Error('What are the chances of another plugin called HayMaker?! Or, is this script being loaded multiple times?...');
}
$.HayMaker = function() {
if (!(this instanceof $.HayMaker)) {
return new $.HayMaker();
}
$.HayMaker.count++;
this.cache = {};
this.queue = [];
this.working = false;
this.session = (window.sessionStorage) ? window.sessionStorage.hay = '' : '';
this.start_time;
// image for capturing preloaded images
var _this = this;
this.img = $('<img />')
.attr({ 'id': 'hay_maker_image_' + $.HayMaker.count, 'style' : 'display: none' })
.load(function() { _this._process(this.src); })
.appendTo(document.body)[0];
};
$.HayMaker.count = 0;
$.HayMaker.prototype = {
queue: function(uris) {
if (typeof uris === 'string') {
this.queue.push(uris);
}
else {
this.queue = this.queues.concat(uris);
}
var _this = this;
$(document)[ ($.HayMaker.waiting) ? 'ajaxStop' : 'ready' ](function() {
$.HayMaker.waiting = false;
_this.start();
});
},
pause: function() {
this.waiting = true;
},
start: function() {
this.start_time = $.now();
this._dequeue();
},
_dequeue: function() {
this.working = (!this.waiting && this.queue.length > 0);
if (!this.working) {
return;
}
var uri = this.queue.shift();
if (this._is_logged(uri)) {
this_dequeue();
}
if (/(.jpg|.png|.gif)$/.test(uri)) {
this.img.src = uri;
}
else {
var _this = this;
$.get(uri, function(data) {
_this._process(uri, data);
});
}
},
_process: function(uri, data) {
if (data) {
this.cache[uri] = data;
}
// if has been loading for more than 300ms, release ui thread
if (this.start_time - $.now() > 300) {
var _this = this;
window.setTimeout(_this.start, 0);
}
else {
this._dequeue();
}
},
_log: function(uri) {
this.session += (uri + ';');
}
_is_logged: function(uri) {
return (this.session.indexOf(uri) > -1);
}
};
// detect start of any initial ajax requests
$(window).ajaxStart(function() {
$.HayMaker.waiting = true;
});
})(jQuery);