2

I've written some code that will check the natural size of an image at load time and if it fits a certain criteria then change the src. The script works fine but for some reason it doesn't work the first time I load the page.

If I refresh the page then the images are replaced as intended. I'm guessing it's something to do with the natural size not being available in the dom but can't seem to find any solution online.

Any help would be appreciated.

Thanks

Steve

Here's my code...

<script type="text/javascript">

jQuery(document).ready(function(){
    jQuery('img').each(function(index){
        // check if browser is html5 compatible or not
        var img = jQuery(this);
        if (typeof img.naturalWidth == "undefined") {
            var newImg = new Image();
            newImg.src = img.attr('src');
            if(newImg.height == 80 && newImg.width == 80){
                jQuery(this).attr("src", "/2/files/no_image.jpg")
            }
        }else{
            if(img.naturalWidth == 80 && img.naturalHeight == 80)jQuery(this).attr("src", "/2/files/no_image.jpg");
        }
    });
});

</script>
Lux Interior
  • 311
  • 4
  • 12
  • 3
    You can't reliably test the image dimensions before the image has been loaded from the source. Your tests of image size should be done in a "load" handler for the image object. – Pointy Sep 10 '15 at 22:43
  • See http://stackoverflow.com/a/545005/2055998 – PM 77-1 Sep 10 '15 at 22:48
  • I changed to window.load instead of document.ready and now it works fine. Thanks! – Lux Interior Sep 10 '15 at 22:49

1 Answers1

1

$(document).ready() runs too soon in the page's lifecycle. If the image is still getting downloaded from the server, you won't have dimensions. Try using $(window).load() instead.

https://stackoverflow.com/a/8396457/120955

Community
  • 1
  • 1
StriplingWarrior
  • 151,543
  • 27
  • 246
  • 315