How to not take images with broken url?
jQuery.each(jQuery('img'), function(k, o) {
imageStack.push(jQuery(o));
});
Only push the images whose load event has fired to imageStack.
To do this, you can bind a load event listener to every image which pushes the image to imageStack.
const imageStack = []
$('img').on('load', function() {
imageStack.push($(this));
})
$(window).on('load', function(){
//wait for every image to load, so imageStack will contain every loaded image
console.log(imageStack)
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img src="https://www.gravatar.com/avatar/0fdacb141bca7fa57c392b5f03872176?s=48&d=identicon&r=PG&f=1">
<img src="brokenurl">
Alternatively, you can wait for every image to load by listening for the window load event, then check the image's naturalWidth property:
const imageStack = []
$(window).on('load', function() {
$('img').each(function() {
if (this.naturalWidth != 0) {
imageStack.push($(this));
}
})
console.log(imageStack)
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img src="https://www.gravatar.com/avatar/0fdacb141bca7fa57c392b5f03872176?s=48&d=identicon&r=PG&f=1">
<img src="brokenurl">