Here's what I am trying to do:
- get all
img
tags from a certaintd
cell. - loop through
img
collection: check if imageloads(exists)
or not. - if image doesn't exists, set the image's
src
attribute todefault
src.
The script:
var default_img = "{{URL::to('/images/default-product-img.jpg')}}";
.
.
.
fnRowCallback: function(nRow, aData, iDisplayIndex, iDisplayIndexFull) {
var s_images = $(nRow).find('td:eq(1) img');
var m_images = $(nRow).find('td:eq(2) img');
var u_images = $(nRow).find('td:eq(3) img');
s_images.each(function(index, element) {
let url = $(this).attr('src');
imageExists(url, function(exists) {
if(!exists) {
$(this).attr({'src': default_img, 'data-exists': exists});
}
});
});
},
The function from this link:
function imageExists(url, callback) {
var img = new Image();
img.onload = function() { callback(true); };
img.onerror = function() { callback(false); };
img.src = url;
}
But images are still not loading, not even the default ones. Neither the data-exists
attribute is set which I've added for test purpose.
e.g url
that I am working with is :
https://cdn.shopify.com/s/files/1/0020/4433/0057/products/0fc643cb997ee029b87b72ea84b2f9c6.jpg?v=1542290204
JSFiddle: https://jsfiddle.net/3smx18o6/1/
What am I missing here? How should the functions be called from the callback
function?