image-promise
Load one or more images, return a promise. Only 0.5KB, for the browser, no dependencies.
It can be used in two ways:
-
pass a URL: it will generate an
<img>
and wait for it to load: -
pass an
<img>
: it will wait for it to load:const img = document; -
pass an array of URLs and/or
<img>
s, wait for them to load:const img = document;
Install
You can just download the standalone bundle (it might take a minute to download)
Or use npm
:
npm install image-promise
// This module is only offered as a ES Module;
Usage
One image
loadImage(image)
will return a Promise that resolves when the image load, or fails when the image
const image = 'cat.jpg';// const image = $('img')[0]; // it can also be an <img> element ;
Multiple images
image-promise
can load multiple images at a time
const images = 'cat.jpg' 'dog.jpg';// const images = $('img'); // it can also be a jQuery object// const images = document.querySelectorAll('img'); // or a NodeList ;
Set custom attributes
loadImage(image, attributes)
lets you pass as the second argument an object of attributes you want to assign to the image element before it starts loading.
This is useful for example when you need CORS enabled image, where you need to set the attribute crossorigin="anonymous"
before the image starts downloading.
const image = 'https://catpics.com/cat.jpg'; ;
Dependencies
None! But you need to polyfill window.Promise
in IE11 and lower.
License
MIT © Federico Brigante