lazyLoad.js
1.4 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
require('intersection-observer');
var imgSrcHandle =require('./img-src-handle');
function lazyLoad(obj) {
var _this = this;
this.conf = {
srcTarget: obj && obj.srcTarget || 'data-src',
selector: obj && obj.selector || '.yo-lazy'
};
this.io = new IntersectionObserver(function (entries) {
entries.forEach(function (entry) {
if (entry.intersectionRatio > 0) {
_this.io.unobserve(entry.target);
var src = entry.target.getAttribute(_this.conf.srcTarget);
if ("img" === entry.target.tagName.toLowerCase()) {
if (src) {
entry.target.src = src;
}
} else {
entry.target.style.backgroundImage = "url(" + imgSrcHandle(src) + ")";
}
entry.target.setAttribute('data-load','false')
}
})
}, {
root: null,
rootMargin: "0px",
threshold: [0]
})
var imgs = document.querySelectorAll(this.conf.selector);
this.loading = function () {
imgs.forEach(function (value) {
_this.io.observe(value);
})
};
}
module.exports = function (obj) {
var lazy = new lazyLoad(obj);
if (typeof window.supportWebp !== 'undefined') {
lazy.loading();
} else {
document.addEventListener('supportWebp', lazy.loading);
}
};