-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathtoad.next.js
More file actions
67 lines (50 loc) · 1.81 KB
/
toad.next.js
File metadata and controls
67 lines (50 loc) · 1.81 KB
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
// This will not work in most browsers
// due to use of passive event listeners, arrow functions, and variable assignment with let
;((win, doc) => {
'use strict';
win.addEventListener('load', toad, { passive: true, capture: false, once: true });
win.addEventListener('scroll', rebounce(toad), { passive: true, capture: false, once: false });
win.addEventListener('resize', rebounce(toad), { passive: true, capture: false, once: false });
function isInViewport (r) {
return r.top >= 0 && r.left >= 0 && r.top <= win.innerHeight;
}
function rebounce (f) {
var scheduled, context, args, i, j;
return function () {
context = this;
args = [];
i = arguments.length;
j = 0;
for (;j < i; ++j) {
args[j] = arguments[j];
}
if (!!scheduled) {
win.cancelAnimationFrame(scheduled);
}
scheduled = win.requestAnimationFrame(() => {
f.apply(context, args);
scheduled = null;
});
}
}
function toad () {
let elements = doc.querySelectorAll('[data-src]') || [];
let i = elements.length;
let j = 0;
for (;j < i; ++j) {
let 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');
}
}
}
}
})(window, window.document);