forked from dkern/jquery.lazy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
jquery.lazy.js
790 lines (678 loc) · 27.6 KB
/
jquery.lazy.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
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
/*!
* jQuery & Zepto Lazy - v1.7.1
* http://jquery.eisbehr.de/lazy/
*
* Copyright 2012 - 2016, Daniel 'Eisbehr' Kern
*
* Dual licensed under the MIT and GPL-2.0 licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl-2.0.html
*
* $("img.lazy").lazy();
*/
;(function(window, undefined) {
"use strict";
// noinspection JSUnresolvedVariable
/**
* library instance - here and not in construct to be shorter in minimization
* @return void
*/
var $ = window.jQuery || window.Zepto,
/**
* unique plugin instance id counter
* @type {number}
*/
lazyInstanceId = 0;
/**
* make lazy available to jquery - and make it a bit more case-insensitive :)
* @access public
* @type {function}
* @param {object} settings
* @return void
*/
$.fn.Lazy = $.fn.lazy = function(settings) {
return new LazyPlugin(this, settings);
};
/**
* helper to add plugins to lazy prototype configuration
* @access public
* @type {function}
* @param {string|Array} names
* @param {string|Array} [elements]
* @param {function} loader
* @return void
*/
$.Lazy = $.lazy = function(names, elements, loader) {
// make second parameter optional
if( $.isFunction(elements) ) {
loader = elements;
elements = [];
}
// exit here if parameter is not a callable function
if( !$.isFunction(loader) ) return;
// make parameters an array of names to be sure
names = $.isArray(names) ? names : [names];
elements = $.isArray(elements) ? elements : [elements];
var config = LazyPlugin.prototype.config,
forced = config._f || (config._f = {});
// add the loader plugin for every name
for( var i = 0, l = names.length; i < l; i++ )
if( config[names[i]] === undefined || $.isFunction(config[names[i]]) )
config[names[i]] = loader;
// add forced elements loader
for( var c = 0, a = elements.length; c < a; c++ )
forced[elements[c]] = names[0];
};
/**
* contains all logic and the whole element handling
* is packed in a private function outside class to reduce memory usage, because it will not be created on every plugin instance
* @access private
* @type {function}
* @param {LazyPlugin} instance
* @param {object} config
* @param {object|Array} items
* @param {object} events
* @param {string} namespace
* @return void
*/
function _executeLazy(instance, config, items, events, namespace) {
/**
* a helper to trigger the 'onFinishedAll' callback after all other events
* @access private
* @type {number}
*/
var _awaitingAfterLoad = 0,
/**
* visible content width
* @access private
* @type {number}
*/
_actualWidth = -1,
/**
* visible content height
* @access private
* @type {number}
*/
_actualHeight = -1,
/**
* determine possibly detected high pixel density
* @access private
* @type {boolean}
*/
_isRetinaDisplay = false,
/**
* dictionary entry for better minimization
* @access private
* @type {string}
*/
_afterLoad = "afterLoad",
/**
* dictionary entry for better minimization
* @access private
* @type {string}
*/
_load = "load",
/**
* dictionary entry for better minimization
* @access private
* @type {string}
*/
_error = "error",
/**
* dictionary entry for better minimization
* @access private
* @type {string}
*/
_img = "img",
/**
* dictionary entry for better minimization
* @access private
* @type {string}
*/
_src = "src",
/**
* dictionary entry for better minimization
* @access private
* @type {string}
*/
_srcset = "srcset",
/**
* dictionary entry for better minimization
* @access private
* @type {string}
*/
_sizes = "sizes",
/**
* dictionary entry for better minimization
* @access private
* @type {string}
*/
_backgroundImage = "background-image";
/**
* initialize plugin
* bind loading to events or set delay time to load all items at once
* @access private
* @return void
*/
function _initialize() {
// detect actual device pixel ratio
// noinspection JSUnresolvedVariable
_isRetinaDisplay = window.devicePixelRatio > 1;
// prepare all initial items
_prepareItems(items);
// if delay time is set load all items at once after delay time
if( config.delay >= 0 ) setTimeout(function() { _lazyLoadItems(true); }, config.delay);
// if no delay is set or combine usage is active bind events
if( config.delay < 0 || config.combined ) {
// create unique event function
events.e = _throttle(config.throttle, function(event) {
// reset detected window size on resize event
if( event.type === "resize" )
_actualWidth = _actualHeight = -1;
// execute 'lazy magic'
_lazyLoadItems(event.all);
});
// create function to add new items to instance
events.a = function(additionalItems) {
_prepareItems(additionalItems);
items.push.apply(items, additionalItems);
};
// create function to get all instance items left
events.g = function() {
// filter loaded items before return in case internal filter was not running until now
return (items = $(items).filter(function() {
return !$(this).data(config.loadedName);
}));
};
// load initial items
_lazyLoadItems();
// bind lazy load functions to scroll and resize event
// noinspection JSUnresolvedVariable
$(config.appendScroll).on("scroll." + namespace + " resize." + namespace, events.e);
}
}
/**
* prepare items before handle them
* @access private
* @param {Array|object|jQuery} items
* @return void
*/
function _prepareItems(items) {
// fetch used configurations before loops
var defaultImage = config.defaultImage,
placeholder = config.placeholder,
imageBase = config.imageBase,
srcsetAttribute = config.srcsetAttribute,
loaderAttribute = config.loaderAttribute,
forcedTags = config._f || {};
// filter items and only add those who not handled yet and got needed attributes available
items = $(items).filter(function() {
var element = $(this),
tag = _getElementTagName(this);
return !element.data(config.handledName) &&
(element.attr(config.attribute) || element.attr(srcsetAttribute) || element.attr(loaderAttribute) || forcedTags[tag] != undefined);
})
// append plugin instance to all elements
.data("plugin_" + config.name, instance);
for( var i = 0, l = items.length; i < l; i++ ) {
var element = $(items[i]),
tag = _getElementTagName(items[i]),
elementImageBase = element.attr(config.imageBaseAttribute) || imageBase;
// generate and update source set if an image base is set
if( tag == _img && elementImageBase && element.attr(srcsetAttribute) )
element.attr(srcsetAttribute, _getCorrectedSrcSet(element.attr(srcsetAttribute), elementImageBase));
// add loader to forced element types
if( forcedTags[tag] != undefined && !element.attr(loaderAttribute) )
element.attr(loaderAttribute, forcedTags[tag]);
// set default image on every element without source
if( tag == _img && defaultImage && !element.attr(_src) )
element.attr(_src, defaultImage);
// set placeholder on every element without background image
else if( tag != _img && placeholder && (!element.css(_backgroundImage) || element.css(_backgroundImage) == "none") )
element.css(_backgroundImage, "url('" + placeholder + "')");
}
}
/**
* the 'lazy magic' - check all items
* @access private
* @param {boolean} [allItems]
* @return void
*/
function _lazyLoadItems(allItems) {
// skip if no items where left
if( !items.length ) {
// destroy instance if option is enabled
if( config.autoDestroy )
// noinspection JSUnresolvedFunction
instance.destroy();
return;
}
var loadTriggered = false,
imageBase = config.imageBase || "",
srcsetAttribute = config.srcsetAttribute,
handledName = config.handledName;
// loop all available items
for( var i = 0, l = items.length; i < l; i++ )
(function(item) {
// item is at least in loadable area
if( allItems || _isInLoadableArea(item) ) {
var element = $(item),
tag = _getElementTagName(item),
attribute = element.attr(config.attribute),
elementImageBase = element.attr(config.imageBaseAttribute) || imageBase,
customLoader = element.attr(config.loaderAttribute);
// is not already handled
if( !element.data(handledName) &&
// and is visible or visibility doesn't matter
(!config.visibleOnly || element.is(":visible")) && (
// and image source or source set attribute is available
(attribute || element.attr(srcsetAttribute)) && (
// and is image tag where attribute is not equal source or source set
(tag == _img && (elementImageBase + attribute != element.attr(_src) || element.attr(srcsetAttribute) != element.attr(_srcset))) ||
// or is non image tag where attribute is not equal background
(tag != _img && elementImageBase + attribute != element.css(_backgroundImage))
) ||
// or custom loader is available
customLoader ))
{
// mark element always as handled as this point to prevent double handling
loadTriggered = true;
element.data(handledName, true);
// load item
_handleItem(element, tag, elementImageBase, customLoader);
}
}
})(items[i]);
// when something was loaded remove them from remaining items
if( loadTriggered )
items = $(items).filter(function() {
return !$(this).data(handledName);
});
}
/**
* load the given element the lazy way
* @access private
* @param {object} element
* @param {string} tag
* @param {string} imageBase
* @param {function} [customLoader]
* @return void
*/
function _handleItem(element, tag, imageBase, customLoader) {
// increment count of items waiting for after load
++_awaitingAfterLoad;
// extended error callback for correct 'onFinishedAll' handling
var errorCallback = function() {
_triggerCallback("onError", element);
_reduceAwaiting();
// prevent further callback calls
errorCallback = $.noop;
};
// trigger function before loading image
_triggerCallback("beforeLoad", element);
// fetch all double used data here for better code minimization
var srcAttribute = config.attribute,
srcsetAttribute = config.srcsetAttribute,
sizesAttribute = config.sizesAttribute,
retinaAttribute = config.retinaAttribute,
removeAttribute = config.removeAttribute,
loadedName = config.loadedName,
elementRetina = element.attr(retinaAttribute);
// handle custom loader
if( customLoader ) {
// on load callback
var loadCallback = function() {
// remove attribute from element
if( removeAttribute )
element.removeAttr(config.loaderAttribute);
// mark element as loaded
element.data(loadedName, true);
// call after load event
_triggerCallback(_afterLoad, element);
// remove item from waiting queue and possibly trigger finished event
// it's needed to be asynchronous to run after filter was in _lazyLoadItems
setTimeout(_reduceAwaiting, 1);
// prevent further callback calls
loadCallback = $.noop;
};
// bind error event to trigger callback and reduce waiting amount
element.off(_error).one(_error, errorCallback)
// bind after load callback to element
.one(_load, loadCallback);
// trigger custom loader and handle response
if( !_triggerCallback(customLoader, element, function(response) {
if( response ) {
element.off(_load);
loadCallback();
}
else {
element.off(_error);
errorCallback();
}
})) element.error();
}
// handle images
else {
// create image object
var imageObj = $(new Image());
// bind error event to trigger callback and reduce waiting amount
imageObj.one(_error, errorCallback)
// bind after load callback to image
.one(_load, function() {
// remove element from view
element.hide();
// set image back to element
// do it as single 'attr' calls, to be sure 'src' is set after 'srcset'
if( tag == _img )
element.attr(_sizes, imageObj.attr(_sizes))
.attr(_srcset, imageObj.attr(_srcset))
.attr(_src, imageObj.attr(_src));
else
element.css(_backgroundImage, "url('" + imageObj.attr(_src) + "')");
// bring it back with some effect!
element[config.effect](config.effectTime);
// remove attribute from element
if( removeAttribute ) {
element.removeAttr(srcAttribute + " " + srcsetAttribute + " " + retinaAttribute + " " + config.imageBaseAttribute);
// only remove 'sizes' attribute, if it was a custom one
if( sizesAttribute !== _sizes )
element.removeAttr(sizesAttribute);
}
// mark element as loaded
element.data(loadedName, true);
// call after load event
_triggerCallback(_afterLoad, element);
// cleanup image object
imageObj.remove();
// remove item from waiting queue and possibly trigger finished event
_reduceAwaiting();
});
// set sources
// do it as single 'attr' calls, to be sure 'src' is set after 'srcset'
var imageSrc = (_isRetinaDisplay && elementRetina ? elementRetina : element.attr(srcAttribute)) || "";
imageObj.attr(_sizes, element.attr(sizesAttribute))
.attr(_srcset, element.attr(srcsetAttribute))
.attr(_src, imageSrc ? imageBase + imageSrc : null);
// call after load even on cached image
imageObj.complete && imageObj.load();
}
}
/**
* check if the given element is inside the current viewport or threshold
* @access private
* @param {object} element
* @return {boolean}
*/
function _isInLoadableArea(element) {
var elementBound = element.getBoundingClientRect(),
direction = config.scrollDirection,
threshold = config.threshold,
vertical = // check if element is in loadable area from top
((_getActualHeight() + threshold) > elementBound.top) &&
// check if element is even in loadable are from bottom
(-threshold < elementBound.bottom),
horizontal = // check if element is in loadable area from left
((_getActualWidth() + threshold) > elementBound.left) &&
// check if element is even in loadable area from right
(-threshold < elementBound.right);
if( direction == "vertical" ) return vertical;
else if( direction == "horizontal" ) return horizontal;
return vertical && horizontal;
}
/**
* receive the current viewed width of the browser
* @access private
* @return {number}
*/
function _getActualWidth() {
return _actualWidth >= 0 ? _actualWidth : (_actualWidth = $(window).width());
}
/**
* receive the current viewed height of the browser
* @access private
* @return {number}
*/
function _getActualHeight() {
return _actualHeight >= 0 ? _actualHeight : (_actualHeight = $(window).height());
}
/**
* get lowercase tag name of an element
* @access private
* @param {object} element
* @returns {string}
*/
function _getElementTagName(element) {
return element.tagName.toLowerCase();
}
/**
* prepend image base to all srcset entries
* @access private
* @param {string} srcset
* @param {string} imageBase
* @returns {string}
*/
function _getCorrectedSrcSet(srcset, imageBase) {
if( imageBase ) {
// trim, remove unnecessary spaces and split entries
var entries = srcset.split(",");
srcset = "";
for( var i = 0, l = entries.length; i < l; i++ )
srcset += imageBase + entries[i].trim() + (i !== l - 1 ? "," : "");
}
return srcset;
}
/**
* helper function to throttle down event triggering
* @access private
* @param {number} delay
* @param {function} callback
* @return {function}
*/
function _throttle(delay, callback) {
var timeout,
lastExecute = 0;
return function(event, ignoreThrottle) {
var elapsed = +new Date() - lastExecute;
function run() {
lastExecute = +new Date();
callback.call(instance, event);
}
timeout && clearTimeout(timeout);
if( elapsed > delay || !config.enableThrottle || ignoreThrottle ) run();
else timeout = setTimeout(run, delay - elapsed);
};
}
/**
* reduce count of awaiting elements to 'afterLoad' event and fire 'onFinishedAll' if reached zero
* @access private
* @return void
*/
function _reduceAwaiting() {
--_awaitingAfterLoad;
// if no items were left trigger finished event
if( !items.length && !_awaitingAfterLoad ) _triggerCallback("onFinishedAll");
}
/**
* single implementation to handle callbacks, pass element and set 'this' to current instance
* @access private
* @param {string|function} callback
* @param {object} [element]
* @param {*} [args]
* @return {boolean}
*/
function _triggerCallback(callback, element, args) {
if( (callback = config[callback]) ) {
// jQuery's internal '$(arguments).slice(1)' are causing problems at least on old iPads
// below is shorthand of 'Array.prototype.slice.call(arguments, 1)'
callback.apply(instance, [].slice.call(arguments, 1));
return true;
}
return false;
}
// if event driven don't wait for page loading
if( config.bind == "event" )
_initialize();
// otherwise load initial items and start lazy after page load
else // noinspection JSUnresolvedVariable
$(window).on(_load + "." + namespace, _initialize);
}
/**
* lazy plugin class constructor
* @constructor
* @access private
* @param {object} elements
* @param {object} settings
* @return {object|LazyPlugin}
*/
function LazyPlugin(elements, settings) {
/**
* this lazy plugin instance
* @access private
* @type {object|LazyPlugin|LazyPlugin.prototype}
*/
var _instance = this,
/**
* this lazy plugin instance configuration
* @access private
* @type {object}
*/
_config = $.extend({}, _instance.config, settings),
/**
* instance generated event executed on container scroll or resize
* packed in an object to be referenceable and short named because properties will not be minified
* @access private
* @type {object}
*/
_events = {},
/**
* unique namespace for instance related events
* @access private
* @type {string}
*/
_namespace = _config.name + "-" + ++lazyInstanceId;
// noinspection JSUndefinedPropertyAssignment
/**
* wrapper to get or set an entry from plugin instance configuration
* much smaller on minify as direct access
* @access public
* @type {function}
* @param {string} entryName
* @param {*} [value]
* @return {LazyPlugin|*}
*/
_instance.config = function(entryName, value) {
if( value === undefined )
return _config[entryName];
_config[entryName] = value;
return _instance;
};
// noinspection JSUndefinedPropertyAssignment
/**
* add additional items to current instance
* @access public
* @param {Array|object|string} items
* @return {LazyPlugin}
*/
_instance.addItems = function(items) {
_events.a && _events.a($.type(items) === "string" ? $(items) : items);
return _instance;
};
// noinspection JSUndefinedPropertyAssignment
/**
* get all left items of this instance
* @access public
* @returns {object}
*/
_instance.getItems = function() {
return _events.g ? _events.g() : {};
};
// noinspection JSUndefinedPropertyAssignment
/**
* force lazy to load all items in loadable area right now
* by default without throttle
* @access public
* @type {function}
* @param {boolean} [useThrottle]
* @return {LazyPlugin}
*/
_instance.update = function(useThrottle) {
_events.e && _events.e({}, !useThrottle);
return _instance;
};
// noinspection JSUndefinedPropertyAssignment
/**
* force lazy to load all available items right now
* this call ignores throttling
* @access public
* @type {function}
* @return {LazyPlugin}
*/
_instance.loadAll = function() {
_events.e && _events.e({all: true}, true);
return _instance;
};
// noinspection JSUndefinedPropertyAssignment
/**
* destroy this plugin instance
* @access public
* @type {function}
* @return undefined
*/
_instance.destroy = function() {
// unbind instance generated events
// noinspection JSUnresolvedFunction, JSUnresolvedVariable
$(_config.appendScroll).off("." + _namespace, _events.e);
// noinspection JSUnresolvedVariable
$(window).off("." + _namespace);
// clear events
_events = {};
return undefined;
};
// start using lazy and return all elements to be chainable or instance for further use
// noinspection JSUnresolvedVariable
_executeLazy(_instance, _config, elements, _events, _namespace);
return _config.chainable ? elements : _instance;
}
/**
* settings and configuration data
* @access public
* @type {object}
*/
LazyPlugin.prototype.config = {
// general
name : "lazy",
chainable : true,
autoDestroy : true,
bind : "load",
threshold : 500,
visibleOnly : false,
appendScroll : window,
scrollDirection : "both",
imageBase : null,
defaultImage : "data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==",
placeholder : null,
delay : -1,
combined : false,
// attributes
attribute : "data-src",
srcsetAttribute : "data-srcset",
sizesAttribute : "data-sizes",
retinaAttribute : "data-retina",
loaderAttribute : "data-loader",
imageBaseAttribute : "data-imagebase",
removeAttribute : true,
handledName : "handled",
loadedName : "loaded",
// effect
effect : "show",
effectTime : 0,
// throttle
enableThrottle : true,
throttle : 250,
// callbacks
beforeLoad : undefined,
afterLoad : undefined,
onError : undefined,
onFinishedAll : undefined
};
})(window);