lazyload-v2.js
1.12 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
import 'intersection-observer';
import $ from 'yoho-jquery';
import lozad from 'lozad';
import imgSrcHandle from './img-src-handle';
/**
* lazyload
*/
const lazyload = (selector, options) => {
options = Object.assign({
threshold: 700 * 2, // 一页大概700px ,提前加载三、四页
data_attribute: 'original'
}, options);
if (selector instanceof $) {
selector = selector.selector;
}
const imgsProcess = () => {
const observer = lozad(selector, {
rootMargin: `${options.threshold / 2}px 0px ${options.threshold}px`, // syntax similar to that of CSS Margin
threshold: 0.1, // ratio of element convergence
load(element) {
let src = element.getAttribute(`data-${options.data_attribute}`);
if (src) {
element.src = imgSrcHandle(src, options);
}
}
});
observer.observe();
};
if (typeof window.supportWebp !== 'undefined') {
imgsProcess();
} else {
$(document).on('supportWebp', imgsProcess);
}
};
module.exports = lazyload;