-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
62 lines (60 loc) · 2.07 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
53
54
55
56
57
58
59
60
61
62
import imagePreloader from './components/imagePreloader.vue'
export default {
install: function (Vue, options) {
document.body.innerHTML = '<img id="imagePreloader_global_component">' + document.body.innerHTML
const globalComponentsStyle = document.getElementById('imagePreloader_global_component').style
globalComponentsStyle.width = 0
globalComponentsStyle.height = 0
globalComponentsStyle.position = 'fixed'
globalComponentsStyle.zIndex = -1
Vue.component('imagePreloader', imagePreloader)
Vue.prototype.$imagePreload = (srcs, element = null, cb = () => null) => {
if(typeof element === "function") {
cb = element
element = null
}
return new Promise((resolve, reject) => {
const data = typeof srcs === "array" ? new Array(srcs) : srcs
const el = element ? element : (document || {}).getElementById('imagePreloader_global_component')
try {
let count = 0
for(let i = 0; i < data.length; i++) {
const src = data[i]
const img = new Image()
img.src = src
img.onload = async () => {
el.style.content = el.style.content + ' url(' + src + ')'
count++
await cb({
element,
src,
index: i,
count,
length: data.length,
progress: count / data.length * 100
})
if(count == data.length) resolve(element ? element : true)
}
img.onerror = reject
}
} catch(e) {
reject(e)
}
})
}
Vue.prototype.$imagePreload.reset = (element = null) => {
return new Promise((resolve, reject) => {
try {
const el = element ? element : (document || {}).getElementById('imagePreloader_global_component')
if(el) {
el.style.content = ''
} else reject(null)
resolve(element ? element : true)
} catch(e) {
reject(e)
}
})
}
}
}
export { imagePreloader }