image-promise
Load an image and return a promise in the browser, in 0.3KB, no dependencies

Install
npm install --save image-promise
import loadImage from 'image-promise';
If you don't use node/babel, include this:
<script src="dist/image-promise.browser.js"></script>
It uses the ES2015 window.Promise
, so if you need to support older browsers (IE<=11) you need a polyfill.
Usage
loadImage( '/cat.jpg' );
loadImage( ['/cat.jpg', '/dog.png'] );
loadImage( document.querySelector('img') );
loadImage( document.querySelectorAll('img') );
Examples
Load one image:
loadImage('cat.jpg')
.then(function (img) {
ctx.drawImage(img, 0, 0, 10, 10);
})
.catch(function () {
console.error('Image failed to load :(');
});
Load multiple images
loadImage(['/cat.jpg', '/dog.png'])
.then(function (allImgs) {
console.log(allImgs.length, 'images loaded!', allImgs);
})
.catch(function (firstImageThatFailed) {
console.error('One or more images have failed to load :(');
});
Automatic cache
If you pass image URLs (first two examples), image-promise
will caches the generated <img>
tags so successive calls with the same exact src
string will return the same <img>
tag and will be resolved at the same time as the first one.
Because the <img>
are cached internally, if you want to uncache and unload them from memory, call the unload
method on the same src
:
loadImage.unload('img.jpg');
Dependencies
None! But you need to polyfill window.Promise
in IE<=11
License
MIT © Federico Brigante