-
Notifications
You must be signed in to change notification settings - Fork 0
/
stik_lazy_image.js
67 lines (56 loc) · 1.8 KB
/
stik_lazy_image.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
stik.boundary({
as: 'lazyImage',
from: 'behavior',
resolvable: true,
to: function($window, $h){
return function(elm, opts){
var obj = {},
offset,
throttle;
if (opts == null) { opts = {}; }
offset = parseInt(opts.offset || 0);
throttle = parseInt(opts.throttle || 250);
function defineListeners(){
if (document.addEventListener) {
$window.addEventListener('scroll', $h.debounce(_throttle, 100), false);
return $window.addEventListener('load', _throttle, false);
} else {
$window.attachEvent('onscroll', $h.debounce(_throttle, 100));
return $window.attachEvent('onload', _throttle);
}
}
function removeListeners(){
if (document.removeEventListener) {
return $window.removeEventListener('scroll', _throttle);
} else {
return $window.detachEvent('onscroll', _throttle);
}
}
function _throttle(){
var poll;
clearTimeout(poll);
return poll = setTimeout(obj.loadImage, throttle);
}
function inView(){
return distanceFromTop() <= consideredArea();
}
function distanceFromTop(){
var coords = elm.getBoundingClientRect();
return coords.top >= 0 && coords.left >= 0 && coords.top;
}
function consideredArea(){
return ($window.innerHeight || document.documentElement.clientHeight) + offset;
}
obj.loadImage = function loadImage(){
if (inView() && elm.hasAttribute('data-src')) {
elm.style.background = 'url(' + elm.getAttribute('data-src') + ')';
elm.removeAttribute('data-src');
return removeListeners();
}
};
defineListeners();
obj.loadImage();
return obj;
};
}
});