forked from dinbror/blazy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
blazy.js
334 lines (305 loc) · 12.7 KB
/
blazy.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
/*!
hey, [be]Lazy.js - v1.6.2 - 2016.05.09
A fast, small and dependency free lazy load script (https://github.com/dinbror/blazy)
(c) Bjoern Klinggaard - @bklinggaard - http://dinbror.dk/blazy
*/
;
(function(root, blazy) {
if (typeof define === 'function' && define.amd) {
// AMD. Register bLazy as an anonymous module
define(blazy);
} else if (typeof exports === 'object') {
// Node. Does not work with strict CommonJS, but
// only CommonJS-like environments that support module.exports,
// like Node.
module.exports = blazy();
} else {
// Browser globals. Register bLazy on window
root.Blazy = blazy();
}
})(this, function() {
'use strict';
//private vars
var _source, _viewport, _isRetina, _attrSrc = 'src',
_attrSrcset = 'srcset';
// constructor
return function Blazy(options) {
//IE7- fallback for missing querySelectorAll support
if (!document.querySelectorAll) {
var s = document.createStyleSheet();
document.querySelectorAll = function(r, c, i, j, a) {
a = document.all, c = [], r = r.replace(/\[for\b/gi, '[htmlFor').split(',');
for (i = r.length; i--;) {
s.addRule(r[i], 'k:v');
for (j = a.length; j--;) a[j].currentStyle.k && c.push(a[j]);
s.removeRule(0);
}
return c;
};
}
//options and helper vars
var scope = this;
var util = scope._util = {};
util.elements = [];
util.destroyed = true;
scope.options = options || {};
scope.options.error = scope.options.error || false;
scope.options.offset = scope.options.offset || 100;
scope.options.success = scope.options.success || false;
scope.options.selector = scope.options.selector || '.b-lazy';
scope.options.separator = scope.options.separator || '|';
scope.options.container = scope.options.container ? document.querySelectorAll(scope.options.container) : false;
scope.options.errorClass = scope.options.errorClass || 'b-error';
scope.options.breakpoints = scope.options.breakpoints || false; // obsolete
scope.options.loadInvisible = scope.options.loadInvisible || false;
scope.options.successClass = scope.options.successClass || 'b-loaded';
scope.options.validateDelay = scope.options.validateDelay || 25;
scope.options.saveViewportOffsetDelay = scope.options.saveViewportOffsetDelay || 50;
scope.options.srcset = scope.options.srcset || 'data-srcset';
scope.options.src = _source = scope.options.src || 'data-src';
_isRetina = window.devicePixelRatio > 1;
_viewport = {};
_viewport.top = 0 - scope.options.offset;
_viewport.left = 0 - scope.options.offset;
/* public functions
************************************/
scope.revalidate = function() {
initialize(this);
};
scope.load = function(elements, force) {
var opt = this.options;
if (elements.length === undefined) {
loadElement(elements, force, opt);
} else {
each(elements, function(element) {
loadElement(element, force, opt);
});
}
};
scope.destroy = function() {
var self = this;
var util = self._util;
if (self.options.container) {
each(self.options.container, function(object) {
unbindEvent(object, 'scroll', util.validateT);
});
}
unbindEvent(window, 'scroll', util.validateT);
unbindEvent(window, 'resize', util.validateT);
unbindEvent(window, 'resize', util.saveViewportOffsetT);
// destroy handler for scroller
if (self.scroller) {
self.scroller._xscroll && self.scroller._xscroll.off("scroll scrollend afterrender", util.validateT, self.scroller._xscroll);
}
util.count = 0;
util.elements.length = 0;
util.destroyed = true;
};
//throttle, ensures that we don't call the functions too often
util.validateT = throttle(function() {
validate(scope);
}, scope.options.validateDelay, scope);
util.saveViewportOffsetT = throttle(function() {
saveViewportOffset(scope.options.offset);
}, scope.options.saveViewportOffsetDelay, scope);
saveViewportOffset(scope.options.offset);
//handle multi-served image src (obsolete)
each(scope.options.breakpoints, function(object) {
if (object.width >= window.screen.width) {
_source = object.src;
return false;
}
});
// start lazy load
setTimeout(function() {
initialize(scope);
}); // "dom ready" fix
};
/* Private helper functions
************************************/
function initialize(self) {
var util = self._util;
// First we create an array of elements to lazy load
util.elements = toArray(self.options.selector);
util.count = util.elements.length;
// Then we bind resize and scroll events if not already binded
if (util.destroyed) {
util.destroyed = false;
if (self.options.container) {
each(self.options.container, function(object) {
bindEvent(object, 'scroll', util.validateT);
});
}
bindEvent(window, 'resize', util.saveViewportOffsetT);
bindEvent(window, 'resize', util.validateT);
bindEvent(window, 'scroll', util.validateT);
// scroll handler for scroller
if (self.options.scroller) {
var scroller = self.options.scroller._xscroll
var eventType = scroller.userConfig.useOriginScroll ? "scroll" : "scrollend";
scroller.on("afterrender", util.validateT, self);
scroller.on(eventType, util.validateT, self);
}
}
// And finally, we start to lazy load.
validate(self);
}
function validate(self) {
var util = self._util;
for (var i = 0; i < util.count; i++) {
var element = util.elements[i];
if (elementInView(element) || hasClass(element, self.options.successClass)) {
self.load(element);
util.elements.splice(i, 1);
util.count--;
i--;
}
}
if (util.count === 0) {
self.destroy();
}
}
function elementInView(ele) {
var rect = ele.getBoundingClientRect();
return (
// Intersection
rect.right >= _viewport.left && rect.bottom >= _viewport.top && rect.left <= _viewport.right && rect.top <= _viewport.bottom
);
}
function loadElement(ele, force, options) {
// if element is visible, not loaded or forced
if (!hasClass(ele, options.successClass) && (force || options.loadInvisible || (ele.offsetWidth > 0 && ele.offsetHeight > 0))) {
var dataSrc = ele.getAttribute(_source) || ele.getAttribute(options.src); // fallback to default 'data-src'
if (dataSrc) {
var dataSrcSplitted = dataSrc.split(options.separator);
var src = dataSrcSplitted[_isRetina && dataSrcSplitted.length > 1 ? 1 : 0];
var isImage = equal(ele, 'img');
// Image or background image
if (isImage || ele.src === undefined) {
var img = new Image();
// using EventListener instead of onerror and onload
// due to bug introduced in chrome v50
// (https://productforums.google.com/forum/#!topic/chrome/p51Lk7vnP2o)
var onErrorHandler = function() {
if (options.error) options.error(ele, "invalid");
addClass(ele, options.errorClass);
unbindEvent(img, 'error', onErrorHandler);
unbindEvent(img, 'load', onLoadHandler);
};
var onLoadHandler = function() {
// Is element an image
if (isImage) {
setSrc(ele, src); //src
handleSource(ele, _attrSrcset, options.srcset); //srcset
//picture element
var parent = ele.parentNode;
if (parent && equal(parent, 'picture')) {
each(parent.getElementsByTagName('source'), function(source) {
handleSource(source, _attrSrcset, options.srcset);
});
}
if (options.scroller) {
options.scroller.reset()
}
// or background-image
} else {
ele.style.backgroundImage = 'url("' + src + '")';
}
itemLoaded(ele, options);
unbindEvent(img, 'load', onLoadHandler);
unbindEvent(img, 'error', onErrorHandler);
};
bindEvent(img, 'error', onErrorHandler);
bindEvent(img, 'load', onLoadHandler);
setSrc(img, src); //preload
} else { // An item with src like iframe, unity, simpelvideo etc
setSrc(ele, src);
itemLoaded(ele, options);
}
} else {
// video with child source
if (equal(ele, 'video')) {
each(ele.getElementsByTagName('source'), function(source) {
handleSource(source, _attrSrc, options.src);
});
ele.load();
itemLoaded(ele, options);
} else {
if (options.error) options.error(ele, "missing");
addClass(ele, options.errorClass);
}
}
}
}
function itemLoaded(ele, options) {
addClass(ele, options.successClass);
if (options.success) options.success(ele);
// cleanup markup, remove data source attributes
ele.removeAttribute(options.src);
each(options.breakpoints, function(object) {
ele.removeAttribute(object.src);
});
}
function setSrc(ele, src) {
ele[_attrSrc] = src;
}
function handleSource(ele, attr, dataAttr) {
var dataSrc = ele.getAttribute(dataAttr);
if (dataSrc) {
ele[attr] = dataSrc;
ele.removeAttribute(dataAttr);
}
}
function equal(ele, str) {
return ele.nodeName.toLowerCase() === str;
}
function hasClass(ele, className) {
return (' ' + ele.className + ' ').indexOf(' ' + className + ' ') !== -1;
}
function addClass(ele, className) {
if (!hasClass(ele, className)) {
ele.className += ' ' + className;
}
}
function toArray(selector) {
var array = [];
var nodelist = document.querySelectorAll(selector);
for (var i = nodelist.length; i--; array.unshift(nodelist[i])) {}
return array;
}
function saveViewportOffset(offset) {
_viewport.bottom = (window.innerHeight || document.documentElement.clientHeight) + offset;
_viewport.right = (window.innerWidth || document.documentElement.clientWidth) + offset;
}
function bindEvent(ele, type, fn) {
if (ele.attachEvent) {
ele.attachEvent && ele.attachEvent('on' + type, fn);
} else {
ele.addEventListener(type, fn, false);
}
}
function unbindEvent(ele, type, fn) {
if (ele.detachEvent) {
ele.detachEvent && ele.detachEvent('on' + type, fn);
} else {
ele.removeEventListener(type, fn, false);
}
}
function each(object, fn) {
if (object && fn) {
var l = object.length;
for (var i = 0; i < l && fn(object[i], i) !== false; i++) {}
}
}
function throttle(fn, minDelay, scope) {
var lastCall = 0;
return function() {
var now = +new Date();
if (now - lastCall < minDelay) {
return;
}
lastCall = now;
fn.apply(scope, arguments);
};
}
});