0

Here's what I am trying to do:

  1. get all img tags from a certain td cell.
  2. loop through img collection: check if image loads(exists) or not.
  3. if image doesn't exists, set the image's src attribute to default 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?

Azima
  • 3,835
  • 15
  • 49
  • 95

0 Answers0