Created
March 27, 2017 14:47
-
-
Save englishextra/3e95d301d1d47fe6e26e3be198f0675e to your computer and use it in GitHub Desktop.
return image is loaded promise
This file contains 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
/*! | |
* return image is loaded promise | |
* @param {String|Object} s image path string or HTML DOM Image Object | |
* imagePromise(path_to_image).then(function (r) { | |
* my_image_object.src = r; | |
* }).catch (function (err) { | |
* console.error("function manageImgLightboxLinks: image failed to load", err); | |
* }); | |
* source: gist.github.com/englishextra/3e95d301d1d47fe6e26e3be198f0675e | |
* passes jshint | |
*/ | |
var imagePromise = function (s) { | |
if (window.Promise) { | |
return new Promise(function (y, n) { | |
var f = function (e, p) { | |
e.onload = function () { | |
y(p); | |
}; | |
e.onerror = function () { | |
n(p); | |
}; | |
e.src = p; | |
}; | |
if ("string" === typeof s) { | |
var a = new Image(); | |
f(a, s); | |
} else { | |
if ("IMG" !== s.tagName) { | |
return Promise.reject(); | |
} else { | |
if (s.src) { | |
f(s, s.src); | |
} | |
} | |
} | |
}); | |
} else { | |
throw new Error("Promise is not in window"); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment