Skip to content

Instantly share code, notes, and snippets.

@twalker
Last active January 3, 2016 14:19
Show Gist options
  • Save twalker/6e8fef3fb2db789b098f to your computer and use it in GitHub Desktop.
Save twalker/6e8fef3fb2db789b098f to your computer and use it in GitHub Desktop.
/**
* ImageReady promises to inform when an image is loaded.
*
* uses es6-promises.
* inspired by: http://www.html5rocks.com/en/tutorials/es6/promises/
*
* @example
* ready(elImg).then(function(img){
* console.log('image is loaded');
* }, function(err){
* console.log('image failed');
* });
*/
define(function(require, exports, module){
var Promise = require('es6-promise');
var ready = function ready(imageOrUrl){
var isUrl = (typeof imageOrUrl === 'string'),
img = isUrl ? new Image() : imageOrUrl;
return new Promise(function(resolve, reject){
if(img.complete && !!img.src && img.naturalWidth !== 0){
resolve(img);
} else {
img.addEventListener('load', function(e) {
resolve(img);
}, false);
img.addEventListener('error', reject, false);
img.addEventListener('error', function(e){console.log('image error',e )}, false);
if(isUrl) img.src = imageOrUrl;
}
});
};
return ready;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment