-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathtoad.js
106 lines (89 loc) · 2.74 KB
/
toad.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
;(function (win, doc) {
if (!('requestAnimationFrame' in win)) {
win.requestAnimationFrame = (function () {
return win.webkitRequestAnimationFrame
|| win.mozRequestAnimationFrame
|| win.oRequestAnimationFrame
|| win.msRequestAnimationFrame
|| function (callback) { return win.setTimeout(callback, 1000/60) };
})();
}
if (!('cancelAnimationFrame' in win)) {
win.cancelAnimationFrame = (function () {
return win.webkitCancelAnimationFrame
|| win.mozCancelAnimationFrame
|| win.oCancelAnimationFrame
|| win.msCancelAnimationFrame
|| function (id) { return win.cancelTimeout(id) };
})();
}
win.toad = {
startListening: start
};
function addEventHandler (ev, h) {
win.addEventListener ?
win.addEventListener(ev, h, !1) :
win.attachEvent ?
win.attachEvent('on' + ev, h) :
win['on' + ev] = h;
}
function removeEventHandler (ev, h) {
win.removeEventListener ?
win.removeEventListener(ev, h, !1) :
win.detachEvent ?
win.detachEvent('on' + ev, h) :
win['on' + ev] = null;
}
function isInViewport (r) {
return r.top >= 0 && r.left >= 0 && r.top <= win.innerHeight;
}
function rebounce (f) {
var scheduled;
var context;
var args;
var len;
var i;
return function () {
context = this;
args = [];
len = arguments.length;
i = 0;
for (;i < len; ++i) {
args[i] = arguments[i];
}
if (!!scheduled) {
win.cancelAnimationFrame(scheduled);
}
scheduled = win.requestAnimationFrame(function () {
f.apply(context, args);
scheduled = null;
});
}
}
function toad () {
var elements = doc.querySelectorAll('[data-src]') || [];
var len = elements.length;
var j = 0;
var this_el;
for (; j < len; ++j) {
this_el = elements[j];
if (!this_el.getAttribute('data-src') || !isInViewport(this_el.getBoundingClientRect())) {
return;
}
if (!!this_el.getAttribute('data-src') && isInViewport(this_el.getBoundingClientRect())) {
if ('img' === this_el.tagName.toLowerCase()) {
this_el.src = this_el.getAttribute('data-src');
this_el.removeAttribute('data-src');
} else {
this_el.style.backgroundImage = 'url(' + this_el.getAttribute('data-src') + ')';
this_el.removeAttribute('data-src');
}
}
}
}
function start () {
addEventHandler('load', rebounce(toad));
addEventHandler('scroll', rebounce(toad));
addEventHandler('resize', rebounce(toad));
}
})(window, window.document);