Last active
January 3, 2016 14:19
-
-
Save twalker/6e8fef3fb2db789b098f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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