-
Notifications
You must be signed in to change notification settings - Fork 0
/
jquery.lazyscript.js
126 lines (101 loc) · 2.7 KB
/
jquery.lazyscript.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
(function (factory) {
if (typeof define === 'function' && define.amd) {
define(['jquery'], factory);
} else {
factory(jQuery);
}
}(function ($) {
var pluginName = "lazyScript", defaults = {
selectorClass: 'lazy',
callback: jQuery.noop,
threshold: 0,
scrollInterval: 500
};
function Plugin (element, options) {
this.element = element;
this.paused = false;
this.$element = $(element);
this.settings = $.extend({}, defaults, options);
this.init();
}
Plugin.prototype = {
init: function () {
var timeout;
var self = this;
this.$element.on('scroll.' + pluginName, function () {
if (timeout) {
return;
}
timeout = setTimeout(function() {
if (!self.paused) {
self.update();
}
timeout = null;
}, self.settings.scrollInterval);
});
setTimeout(function () {
self.update();
}, 13);
},
pause: function () {
this.paused = true;
},
resume: function () {
this.paused = false;
},
destroy: function () {
this.$element.off('.' + pluginName);
},
update: function () {
var self = this;
$('.' + self.settings.selectorClass).each(function () {
var $this = $(this);
if (self.inViewport($this)) {
if (self.settings.callback.call(this, $this) !== false) {
$this.removeClass(self.settings.selectorClass);
}
}
});
},
inViewport: function ($element) {
var offset = $element.offset(),
threshold = this.settings.threshold,
$window = this.$element;
if (($window.height() + $window.scrollTop()) <= (offset.top - threshold)) {
return false;
}
if (($window.width() + $window.scrollLeft()) <= (offset.left - threshold)) {
return false;
}
if ($window.scrollTop() > (offset.top + threshold + $element.height())) {
return false;
}
if ($window.scrollLeft() > (offset.left + threshold + $element.width())) {
return false;
}
return true;
}
};
$.fn[pluginName] = function (options) {
if ((options === undefined) || (typeof options === 'object')) {
return this.each(function () {
if (!$.data(this, "plugin_" + pluginName)) {
$.data(this, "plugin_" + pluginName, new Plugin(this, options));
}
});
}
if ((typeof options === 'string') && (options[0] !== '_') && (options !== 'init')) {
var returns, args = arguments;
this.each(function () {
var instance = $.data(this, 'plugin_' + pluginName);
if ((instance instanceof Plugin) && (typeof instance[options] === 'function')) {
returns = instance[options].apply(instance, Array.prototype.slice.call(args, 1));
}
if (options === 'destroy') {
$.data(this, 'plugin_' + pluginName, null);
}
});
return returns !== undefined ? returns : this;
}
};
}));