-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathenhanceAppFile.js
52 lines (48 loc) · 1.26 KB
/
enhanceAppFile.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
import config from '@dynamic/imgLazy'
export default ({ Vue }) => {
Vue.mixin({
data() {
return {
$io: undefined
}
},
mounted() {
const lazyEls = document.querySelectorAll('img.' + config.selector)
if (config.useNative && 'loading' in HTMLImageElement.prototype) {
lazyEls.forEach(lazyEl => {
!lazyEl.getAttribute('src') && lazyEl.setAttribute('src', lazyEl.getAttribute('data-src'))
})
} else {
this.setObserver()
lazyEls.forEach(lazyEl => {
this.$io.observe(lazyEl)
})
}
},
methods: {
setObserver() {
this.$io = new IntersectionObserver(entries => {
entries.forEach(item => {
if (item.isIntersecting) {
const src = this.getSrc(item.target)
if (src) {
item.target.src = src
}
this.$io.unobserve(item.target)
}
})
}, {
rootMargin: config.rootMargin
})
},
getSrc(el) {
if (el.dataset) {
return el.dataset.src
} else {
const item = el.attributes.find(item => item.nodeName === 'data-src')
return item && item.nodeValue
}
}
}
})
}