Created
November 29, 2015 10:52
-
-
Save radist2s/706fbc3091949cf88e13 to your computer and use it in GitHub Desktop.
Images loaded simple checker with promises
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
define(['promise'], function () { | |
// Use any Promise polyfill | |
var imgClasses = [HTMLImageElement], | |
imgElementsList = ['img'] | |
if (window.HTMLPictureElement) { | |
imgClasses.push(HTMLPictureElement) | |
imgElementsList.push('picture') | |
} | |
imgElementsList = imgElementsList.join() | |
function isAlreadyLoadedImage(img) { | |
if (!img.complete) { | |
return false | |
} | |
return !!img.naturalWidth | |
} | |
function isBrokenImage(img) { | |
return img.complete && !img.naturalWidth | |
} | |
function onLoad(resolve) { | |
resolve() | |
} | |
function onError(reject) { | |
reject() | |
} | |
function offEvents(imgListenerLoad, imgListenerError) { | |
this.removeEventListener('load', imgListenerLoad) | |
this.removeEventListener('error', imgListenerError) | |
} | |
function isImage(element) { | |
return imgClasses.some(function (imgClass) { | |
return element instanceof imgClass | |
}) | |
} | |
return function imagesLoaded($element) { | |
if (!$element) { | |
return Promise.all([]) | |
} | |
if (window.jQuery && $element instanceof window.jQuery || (window.Zepto && Zepto.zepto.Z === $element.constructor)) { | |
$element = $element.get() | |
} | |
if ($element.length === undefined) { | |
$element = [$element] | |
} | |
var promises = [] | |
Array.prototype.forEach.call($element, function (img) { | |
if (!isImage(img)) { | |
return promises.push(imagesLoaded(img.querySelectorAll(imgElementsList))) | |
} | |
var imgListenerLoad, | |
imgListenerError | |
var promise = new Promise(function (resolve, reject) { | |
if (isAlreadyLoadedImage(img)) { | |
return resolve() | |
} | |
if (isBrokenImage(img)) { | |
return reject() | |
} | |
img.addEventListener('load', imgListenerLoad = onLoad.bind(img, resolve)) | |
img.addEventListener('error', imgListenerError = onError.bind(img, reject)) | |
}) | |
var undelegate = offEvents.bind(img, imgListenerLoad, imgListenerError) | |
promise.then(undelegate, undelegate) | |
promises.push(promise) | |
}) | |
return Promise.all(promises) | |
} | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment