-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
52 lines (44 loc) · 1.08 KB
/
index.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
const opts = {
root: null,
rootMargin: "0px",
threshold: [0]
}
function prefetch(url) {
return fetch(url, {credentials: `include`, cache: 'force-cache'}).then(async res => await res.blob())
}
function loadSrc(target, io){
target.removeAttribute('srcset');
io.unobserve(target);
}
const io = new IntersectionObserver((entries) => {
entries.forEach(({isIntersecting, target}) => {
if(isIntersecting){
loadSrc(target, io);
const link = target.getAttribute('link');
if(link){
target.addEventListener('load', () => prefetch(link), {once: true});
}
}
})
}, opts);
export default class LazyLoadable extends HTMLImageElement {
constructor(width, height){
super(width, height);
}
get loading(){
return this.getAttribute('loading')
}
get isModern(){
return ('loading' in HTMLImageElement.prototype)
}
connectedCallback(){
if(this.loading === 'lazy'){
return io.observe(this);
}
// default behaviour is to eagerly load the image
loadSrc(this, io);
}
disconnectedCallback(){
io.unobserve(this);
}
}