forked from swordensen/useful-scripts
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlazy-load-images.js
More file actions
116 lines (97 loc) · 2.73 KB
/
lazy-load-images.js
File metadata and controls
116 lines (97 loc) · 2.73 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
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
class LazyImageLoader {
constructor(){
this.images = document.querySelectorAll("[data-src]");
this.imageCount = this.images.length;
this.config = {
rootMargin: "50px 0px",
threshold: 0.01
};
this.main();
}
main(){
// if intersection observer doesn't exist just load the image
if (typeof window["IntersectionObserver"] === "undefined") {
this.loadImagesImmediately(this.images);
} else {
// create the observer
this.observer = new IntersectionObserver(this.onIntersection.bind(this), this.config);
this.images.forEach(image => {
if(!image.classList.contains("js-lazy-image--handled")){
this.observer.observe(image);
}
})
}
}
fetchImage(url){
return new Promise(function(resolve, reject) {
var image = new Image();
image.src = url;
image.onload = resolve;
image.onerror = reject;
});
}
preloadImage(image){
if (image !== "0") {
var src = image.getAttribute("data-src");
}
if (!src) {
return;
}
return this.fetchImage(src).then(()=> {
this.applyImage(image, src);
});
}
loadImagesImmediately(images){
for (var i = 0; i < this.imageCount; i++) {
this.preloadImage(images[i]);
}
}
onIntersection(entries){
if (this.imageCount === 0) {
this.observer.disconnect();
}
entries.forEach(entry => {
if (entry.intersectionRatio > 0) {
this.imageCount--;
this.observer.unobserve(entry.target);
this.preloadImage(entry.target);
}
});
}
createSVG(img,src){
var imgID = img.getAttribute('id');
var imgClass = img.getAttribute('class');
var requestSVG = new XMLHttpRequest();
requestSVG.open('GET', src, true);
requestSVG.send();
requestSVG.onload = function(e) {
if (requestSVG.status >= 200 && requestSVG.status < 400) {
// Success!
var svg = requestSVG.responseXML.querySelector('svg');
svg.getAttribute('xmlns:a') && svg.removeAttr('xmlns:a');
if (imgID ) {
svg.setAttribute('id', imgID);
}
if ( imgClass ) {
svg.setAttribute('class', imgClass + ' replaced-svg');
}
img.replaceWith(svg);
}
}
}
applyImage(img, src){
img.classList.add("js-lazy-image--handled");
if (img.tagName === "IMG"){
if (img.classList.contains('svg')) {
this.createSVG(img, src);
}else{
img.src = src;
}
} else {
img.style.backgroundImage = `url('${src}')`;
}
console.log("applied image", src);
document.body.classList.add('lazy-loaded');
}
}
const lazyImageLoader = new LazyImageLoader();