-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlazy.js
85 lines (71 loc) · 3.21 KB
/
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
function lazyLoadInit() {
var lazyImages = [].slice.call(document.querySelectorAll('img.lazy'));
var lazyVideos = [].slice.call(document.querySelectorAll("video.lazy"));
if ('IntersectionObserver' in window) {
var lazyImageObserver = new IntersectionObserver(function (entries, observer) {
entries.forEach(function (entry) {
if (entry.isIntersecting) {
var lazyImage = entry.target;
lazyImage.src = lazyImage.dataset.src;
entry.target.onload = function() {
lazyImage.parentNode.classList.add("lazy-inner-loaded");
lazyImage.classList.add("lazy-loaded");
}
lazyImageObserver.unobserve(lazyImage);
}
});
});
var lazyVideoObserver = new IntersectionObserver(function (entries, observer) {
entries.forEach(function (video) {
if (video.isIntersecting) {
for (var source in video.target.children) {
var videoSource = video.target.children[source];
if (typeof videoSource.tagName === "string" && videoSource.tagName === "SOURCE") {
videoSource.src = videoSource.dataset.src;
}
}
video.target.load();
video.target.onloadeddata = function() {
if(video.target.dataset.autoplay == "true") {
video.target.play();
}
video.target.classList.remove("lazy");
video.target.classList.add("lazy-loaded");
video.target.parentNode.classList.add("lazy-inner-loaded");
};
lazyVideoObserver.unobserve(video.target);
}
});
});
lazyImages.forEach(function (lazyImage) {
lazyImageObserver.observe(lazyImage);
});
lazyVideos.forEach(function (lazyVideo) {
lazyVideoObserver.observe(lazyVideo);
});
} else {
lazyImages.forEach(function (lazyImage) {
lazyImage.src = lazyImage.dataset.src;
lazyImage.parentNode.classList.add("lazy-inner-loaded");
lazyImage.classList.add("lazy-loaded");
});
lazyVideos.forEach(function (lazyVideo) {
for (var source in lazyVideo.children) {
var videoSource = lazyVideo.children[source];
if (typeof videoSource.tagName === "string" && videoSource.tagName === "SOURCE") {
videoSource.src = videoSource.dataset.src;
lazyVideo.load();
if(videoSource.dataset.autoplay == "true") {
lazyVideo.play();
}
lazyVideo.classList.add("lazy-loaded");
lazyVideo.classList.remove("lazy");
lazyVideo.parentNode.classList.add("lazy-inner-loaded");
}
}
});
}
}
document.addEventListener('DOMContentLoaded', function () {
lazyLoadInit();
});