-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.next.js
49 lines (40 loc) · 1.28 KB
/
index.next.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
import { add, remove } from 'bianco.events'
import domToArray from 'bianco.dom-to-array'
/**
* Preload any image
* @param { string|HTMLElement } img - Path to the image or image object
* @returns { Promise } a promise that will be resolved when the image will be completely loaded
*/
export function loadImage(img) {
const isUrl = typeof img === 'string'
const i = isUrl ? document.createElement('img') : img
// this image was already loaded
if (!isUrl && i.complete) return Promise.resolve(i)
// the image reference will set to null
// to avoid memory leaks
return new Promise((resolve, reject) => {
const onSuccess = () => {
remove(i, 'error abort', onError)
resolve(i)
}
const onError = error => {
remove(i, 'load', onSuccess)
reject(new Error(error))
}
add(i, 'error abort', onError, { once: true })
add(i, 'load', onSuccess, { once: true })
if (isUrl) i.src = img
})
}
/**
* Load in parallel a collection of images
* @param { Array|NodeList } imgs - array of strings or <img> HTML elements
* @returns { Promise } a promise that will be resolved when all the images will be loaded
*/
export function loadImages(imgs) {
return Promise.all(domToArray(imgs).map(loadImage))
}
export default {
loadImage,
loadImages
}