-
Notifications
You must be signed in to change notification settings - Fork 3
/
jquery.lazyloadxt.js
312 lines (255 loc) · 9.27 KB
/
jquery.lazyloadxt.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
/*jslint browser:true, plusplus:true, vars:true */
/*jshint browser:true, jquery:true */
/*jshint -W040:false */ /* to don't alert on "this" in triggerLoadOrError */
(function ($, window, document, undefined) {
'use strict';
// options
var lazyLoadXT = 'lazyLoadXT',
dataLazied = 'lazied',
load_error = 'load error',
classLazyHidden = 'lazy-hidden',
docElement = document.documentElement || document.body,
// force load all images in Opera Mini and some mobile browsers without scroll event or getBoundingClientRect()
forceLoad = (window.onscroll === undefined || !!window.operamini || !docElement.getBoundingClientRect),
options = {
autoInit: true, // auto initialize in $.ready
selector: 'img[data-src]', // selector for lazyloading elements
blankImage: 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7',
throttle: 99, // interval (ms) for changes check
forceLoad: forceLoad, // force auto load all images
loadEvent: 'pageshow', // check AJAX-loaded content in jQueryMobile
updateEvent: 'load orientationchange resize scroll touchmove focus', // page-modified events
forceEvent: '', // force loading of all elements
//onstart: null,
oninit: {removeClass: 'lazy'}, // init handler
onshow: {addClass: classLazyHidden}, // start loading handler
onload: {removeClass: classLazyHidden, addClass: 'lazy-loaded'}, // load success handler
onerror: {removeClass: classLazyHidden}, // error handler
//oncomplete: null, // complete handler
//scrollContainer: undefined,
checkDuplicates: true
},
elementOptions = {
srcAttr: 'data-src',
edgeX: 0,
edgeY: 0,
visibleOnly: true
},
$window = $(window),
$isFunction = $.isFunction,
$extend = $.extend,
$data = $.data || function (el, name) {
return $(el).data(name);
},
elements = [],
topLazy = 0,
/*
waitingMode=0 : no setTimeout
waitingMode=1 : setTimeout, no deferred events
waitingMode=2 : setTimeout, deferred events
*/
waitingMode = 0;
$[lazyLoadXT] = $extend(options, elementOptions, $[lazyLoadXT]);
/**
* Return options.prop if obj.prop is undefined, otherwise return obj.prop
* @param {*} obj
* @param {*} prop
* @returns *
*/
function getOrDef(obj, prop) {
return obj[prop] === undefined ? options[prop] : obj[prop];
}
/**
* @returns {number}
*/
function scrollTop() {
var scroll = window.pageYOffset;
return (scroll === undefined) ? docElement.scrollTop : scroll;
}
/**
* Add new elements to lazy-load list:
* $(elements).lazyLoadXT() or $(window).lazyLoadXT()
*
* @param {object} [overrides] override global options
*/
$.fn[lazyLoadXT] = function (overrides) {
overrides = overrides || {};
var blankImage = getOrDef(overrides, 'blankImage'),
checkDuplicates = getOrDef(overrides, 'checkDuplicates'),
scrollContainer = getOrDef(overrides, 'scrollContainer'),
forceShow = getOrDef(overrides, 'show'),
elementOptionsOverrides = {},
prop;
// empty overrides.scrollContainer is supported by both jQuery and Zepto
$(scrollContainer).on('scroll', queueCheckLazyElements);
for (prop in elementOptions) {
elementOptionsOverrides[prop] = getOrDef(overrides, prop);
}
return this.each(function (index, el) {
if (el === window) {
$(options.selector).lazyLoadXT(overrides);
} else {
var duplicate = checkDuplicates && $data(el, dataLazied),
$el = $(el).data(dataLazied, forceShow ? -1 : 1);
// prevent duplicates
if (duplicate) {
queueCheckLazyElements();
return;
}
if (blankImage && el.tagName === 'IMG' && !el.src) {
el.src = blankImage;
}
// clone elementOptionsOverrides object
$el[lazyLoadXT] = $extend({}, elementOptionsOverrides);
triggerEvent('init', $el);
elements.push($el);
queueCheckLazyElements();
}
});
};
/**
* Process function/object event handler
* @param {string} event suffix
* @param {jQuery} $el
*/
function triggerEvent(event, $el) {
var handler = options['on' + event];
if (handler) {
if ($isFunction(handler)) {
handler.call($el[0]);
} else {
if (handler.addClass) {
$el.addClass(handler.addClass);
}
if (handler.removeClass) {
$el.removeClass(handler.removeClass);
}
}
}
$el.trigger('lazy' + event, [$el]);
// queue next check as images may be resized after loading of actual file
queueCheckLazyElements();
}
/**
* Trigger onload/onerror handler
* @param {Event} e
*/
function triggerLoadOrError(e) {
triggerEvent(e.type, $(this).off(load_error, triggerLoadOrError));
}
/**
* Load visible elements
* @param {bool} [force] loading of all elements
*/
function checkLazyElements(force) {
if (!elements.length) {
return;
}
force = force || options.forceLoad;
topLazy = Infinity;
var viewportTop = scrollTop(),
viewportHeight = window.innerHeight || docElement.clientHeight,
viewportWidth = window.innerWidth || docElement.clientWidth,
i,
length;
for (i = 0, length = elements.length; i < length; i++) {
var $el = elements[i],
el = $el[0],
objData = $el[lazyLoadXT],
removeNode = false,
visible = force || $data(el, dataLazied) < 0,
topEdge;
// remove items that are not in DOM
if (!$.contains(docElement, el)) {
removeNode = true;
} else if (force || !objData.visibleOnly || el.offsetWidth || el.offsetHeight) {
if (!visible) {
var elPos = el.getBoundingClientRect(),
edgeX = objData.edgeX,
edgeY = objData.edgeY;
topEdge = (elPos.top + viewportTop - edgeY) - viewportHeight;
visible = (topEdge <= viewportTop && elPos.bottom > -edgeY &&
elPos.left <= viewportWidth + edgeX && elPos.right > -edgeX);
}
if (visible) {
$el.on(load_error, triggerLoadOrError);
triggerEvent('show', $el);
var srcAttr = objData.srcAttr,
src = $isFunction(srcAttr) ? srcAttr($el) : el.getAttribute(srcAttr);
if (src) {
el.src = src;
}
removeNode = true;
} else {
if (topEdge < topLazy) {
topLazy = topEdge;
}
}
}
if (removeNode) {
elements.splice(i--, 1);
length--;
}
}
if (!length) {
triggerEvent('complete', $(docElement));
}
}
/**
* Run check of lazy elements after timeout
*/
function timeoutLazyElements() {
if (waitingMode > 1) {
waitingMode = 1;
checkLazyElements();
setTimeout(timeoutLazyElements, options.throttle);
} else {
waitingMode = 0;
}
}
/**
* Queue check of lazy elements because of event e
* @param {Event} [e]
*/
function queueCheckLazyElements(e) {
if (!elements.length) {
return;
}
// fast check for scroll event without new visible elements
if (e && e.type === 'scroll' && e.currentTarget === window) {
if (topLazy >= scrollTop()) {
return;
}
}
if (!waitingMode) {
setTimeout(timeoutLazyElements, 0);
}
waitingMode = 2;
}
/**
* Initialize list of hidden elements
*/
function initLazyElements() {
$window.lazyLoadXT();
}
/**
* Loading of all elements
*/
function forceLoadAll() {
checkLazyElements(true);
}
/**
* Initialization
*/
$(document).ready(function () {
triggerEvent('start', $window);
$window
.on(options.loadEvent, initLazyElements)
.on(options.updateEvent, queueCheckLazyElements)
.on(options.forceEvent, forceLoadAll);
$(document).on(options.updateEvent, queueCheckLazyElements);
if (options.autoInit) {
initLazyElements(); // standard initialization
}
});
})(window.jQuery || window.Zepto || window.$, window, document);