Promise based image loader for the browser
script tag
<script src="image-loader.min.js"></script>
npm
coming soon...
The imageLoader
function returns a promise that resolve on images load.
imageLoader('http://placehold.it/400x400').then(info => {
console.log('Image loaded!', info)
})
const images = ['http://placehold.it/400x400', 'http://placehold.it/200x200']
imageLoader(images).then(info => {
console.log('Images loaded!', info)
})
NOTE: Object must have url
property. ref
property is optional. Any other properties will be ignored
const images = [
{
url: 'http://placehold.it/400x400',
ref: { id: 1 }
},
{
url: 'http://placehold.it/300x300',
ref: { id: 2 }
}
]
imageLoader(images).then(info => {
console.log('Images loaded!', info)
})
URLs will be loaded from DOM (<img>
tags)
imageLoader().then(info => {
console.log('Images loaded!', info)
})
You can pass a callback function to get information about loader status and current loaded image.
const images = ['http://placehold.it/400x400', 'http://placehold.it/300x300']
imageLoader(images, (status, loadedImage) => {
console.log('Status: ', status)
console.log('Loaded image: ', loadedImage)
}).then(info => {
console.log('Images loaded!', info)
})
status
loaded
Number of loaded imagesall
Number of all imagespercent
(Math.round(100 * loaded / all)
)
loadedImage
time
Request duration (ms)url
Image URLref
Reference passed with this imageerror
Any error occurs?
const loaderEl = document.querySelector('.loader')
const statusEl = document.querySelector('.loader__status')
imageLoader(status => {
statusEl.textContent = status.percent + '%'
}).then(info => {
loaderEl.classList.add('loader--hidden')
})
fetchUsers().then(users => {
// ... set avatars img src
const avatars = users.map(user => {
return {
url: user.avatar_URL,
ref: user.id
}
})
const onAvatarLoaded = (loaderStatus, loadedImage) => {
// ... hide loader from user avatar
}
return imageLoader(avatars, onAvatarLoaded)
}).then(avatarsInfo => {
// ... all avatars have loaded
})