forked from sjwilliams/laziestloader
-
Notifications
You must be signed in to change notification settings - Fork 0
/
jquery.laziestloader.js
327 lines (274 loc) · 9.18 KB
/
jquery.laziestloader.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
/**
* @preserve LaziestLoader - v0.7.3 - 2016-01-03
* A responsive lazy loader for jQuery.
* http://sjwilliams.github.io/laziestloader/
* Copyright (c) 2016 Josh Williams; Licensed MIT
*/
(function(factory) {
if (typeof define === 'function' && define.amd) {
define(['jquery'], factory);
} else {
factory(jQuery);
}
}(function($) {
var laziestLoader = function(options, callback) {
var $w = $(window),
$elements = this,
$loaded = $(), // elements with the correct source set
retina = window.devicePixelRatio > 1,
didScroll = false;
options = $.extend(true, {
threshold: 0,
sizePattern: /{{SIZE}}/ig,
getSource: getSource,
event: 'scroll',
scrollThrottle: 250, // time in ms to throttle scroll. Increase for better performance.
sizeOffsetPercent: 0, // prefer smaller images
setSourceMode: true // plugin sets source attribute of the element. Set to false if you would like to, instead, use the callback to completely manage the element on trigger.
}, options);
var useNativeScroll = (typeof options.event === 'string') && (options.event.indexOf('scroll') === 0);
/**
* Generate source path of image to load. Take into account
* type of data supplied and whether or not a retina
* image is available.
*
* Basic option: data attributes specifing a single image to load,
* regardless of viewport.
* Eg:
*
* <img data-src="yourimage.jpg">
* <img data-src="yourimage.jpg" data-src-retina="yourretinaimage.jpg">
*
* Range of sizes: specify a string path with a {{size}} that
* will be replaced by an integer from a list of available sizes.
* Eg:
*
* <img data-pattern="path/toyourimage-{{size}}.jpg" data-widths="[320, 640, 970]">
* <img data-pattern="path/toyourimage-{{size}}.jpg" data-pattern-retina="path/toyourimage-{{size}}@2x.jpg" data-widths="[320, 640, 970]">
* <img data-pattern="path/toyourimage/{{size}}/slug.jpg" data-pattern-retina="path/toyourimage/{{size}}/[email protected]" data-widths="[320, 640, 970]">
*
* Range of sizes, with slugs: specify a string path with a {{size}} that
* will be replaced by a slug representing an image size.
* Eg:
*
* <img data-pattern="path/toyourimage-{{size}}.jpg" data-widths="[{width: 320, slug: 'small'},{width:900, slug: 'large'}]">
*
* @param {jQuery object} $el
* @return {String}
*/
function getSource($el) {
var source, slug;
var data = $el.data();
if (data.pattern && data.widths && $.isArray(data.widths)) {
source = retina ? data.patternRetina : data.pattern;
source = source || data.pattern;
// width or slug version?
if (typeof data.widths[0] === 'object') {
slug = (function() {
var widths = $.map(data.widths, function(val) {
return val.size;
});
var bestFitWidth = bestFit($el.width(), widths);
// match best width back to its corresponding slug
for (var i = data.widths.length - 1; i >= 0; i--) {
if (data.widths[i].size === bestFitWidth) {
return data.widths[i].slug;
}
}
})();
source = source.replace(options.sizePattern, slug);
} else {
source = source.replace(options.sizePattern, bestFit($el.width(), data.widths));
}
} else {
source = retina ? data.srcRetina : data.src;
source = source || data.src;
}
return source;
}
/**
* Reflect loaded state in class names
* and fire event.
*
* @param {jQuery Object} $el
*/
function onLoad($el) {
$el.addClass('ll-loaded').removeClass('ll-notloaded');
$el.trigger('loaded');
if (typeof callback === 'function') {
callback.call($el);
}
}
/**
* Attach event handler that sets correct
* media source for the elements' width, or
* allows callback to manipulate element
* exclusively.
*/
function bindLoader() {
$elements.one('laziestloader', function() {
var $el = $(this);
var source;
// set height?
if ($el.data().ratio) {
setHeight.call(this);
}
// set content. default: set element source
if (options.setSourceMode) {
source = options.getSource($el);
if (source && this.getAttribute('src') !== source) {
this.setAttribute('src', source);
}
}
// applied immediately to reflect that media has started but,
// perhaps, hasn't finished downloading.
$el.addClass('ll-loadstarted');
// Determine when to fire `loaded` event. Wait until
// media is truly loaded if possible, otherwise immediately.
if (options.setSourceMode && (this.nodeName === 'IMG' || this.nodeName === 'VIDEO' || this.nodeName === 'AUDIO') ) {
if (this.nodeName === 'IMG') {
this.onload = function() {
onLoad($el);
};
} else {
this.onloadstart = function() {
onLoad($el);
};
}
} else {
onLoad($el);
}
});
}
/**
* Remove even handler from elements
*/
function unbindLoader() {
$elements.off('laziestloader');
}
/**
* Find the best sized image, opting for larger over smaller
*
* @param {Number} targetWidth element width
* @param {Array} widths array of numbers
* @return {Number}
*/
var bestFit = laziestLoader.bestFit = function(targetWidth, widths) {
var selectedWidth = widths[widths.length - 1],
i = widths.length,
offset = targetWidth * (options.sizeOffsetPercent / 100);
// sort smallest to largest
widths.sort(function(a, b) {
return a - b;
});
while (i--) {
if ((targetWidth - offset) <= widths[i]) {
selectedWidth = widths[i];
}
}
return selectedWidth;
};
/**
* Cycle through elements that haven't had their
* source set and, if they're in the viewport within
* the threshold, load their media
*/
function laziestloader() {
var docEl = document.documentElement;
var wHeight = window.innerHeight || docEl.clientHeight;
var wWidth = window.innerWidth || docEl.clientWidth;
var threshold = options.threshold;
var $inview = $elements.not($loaded).filter(function() {
if ($(this).is(':hidden')) return;
var rect = $(this)[0].getBoundingClientRect();
return (
rect.bottom + threshold > 0 &&
rect.right + threshold > 0 &&
rect.left < wWidth + threshold &&
rect.top < wHeight + threshold
);
});
$inview.trigger('laziestloader');
$loaded.add($inview);
}
/**
* Given a lazy element, check if it should have
* its height set based on a data-ratio multiplier.
*/
function setHeight() {
var $el = $(this),
data = $el.data();
data.ratio = data.ratio || data.heightMultiplier; // backwards compatible for old data-height-multiplier code.
if (data.ratio) {
$el.css({
height: Math.round($el.width() * data.ratio)
});
}
}
// add inital state classes, and check if
// element dimensions need to be set.
$elements.addClass('ll-init ll-notloaded').each(setHeight);
// initial binding
bindLoader();
// Watch either native scroll events, throttled by
// options.scrollThrottle, or a custom event that
// implements its own throttling.
if (useNativeScroll) {
$w.scroll(function(){
didScroll = true;
});
setInterval(function() {
if (didScroll) {
didScroll = false;
laziestloader();
}
}, options.scrollThrottle);
} else {
// if custom event is a function, it'll need
// to call laziestloader() manually, like so:
//
// $('.g-lazy').laziestloader({
// event: function(cb){
// // custom scroll event on nytimes.com
// PageManager.on('nyt:page-scroll', function(){
// // do something interesting if you like
// // and then call the passed in laziestloader();
// cb();
// });
// }
// });
//
//
// Otherwise, it's a string representing an event on the
// window to subscribe to, like so:
//
// // some code dispatching throttled events
// $window.trigger('nytg-scroll');
//
// $('.g-lazy').laziestloader({
// event: 'nytg-scroll'
// });
//
if (typeof options.event === 'function') {
options.event(laziestloader);
} else {
$w.on(options.event, function(){
laziestloader();
});
}
}
// reset state on resize
$w.resize(function() {
$loaded = $();
unbindLoader();
bindLoader();
laziestloader();
});
// initial check for lazy images
$(document).ready(function() {
laziestloader();
});
return this;
};
$.fn.laziestloader = laziestLoader;
}));