In Chrome the currentSrc of an img element is sometimes empty. How can I prevent this?

1k views Asked by At

UPDATE:

I just found some more info. It seems that in Chrome, the currentSrc of the image will often be empty, whereas in Firefox, the URL is always correct. Is the JS trying to access currentSrc before it's available? Is there a way to prevent this?


I am creating a Drupal 8 website, and in order to use the responsive images module with a background-image, I came up with the following workaround. The JS function below, setParallaxImage(), takes the currentSrc from the img in the picture element and sets it as the background-image for the outermost div. The img itself is not displayed (display: none in CSS) and is given a dummy image, as I only need it to get the currentSrc. The function is called with onload and onresize.

The code seems to work well in Firefox. When resizing the browser past a breakpoint, the image goes grey for a split second, then loads the image from the proper source. However, with Chrome, when quickly resizing past a breakpoint, the image may become grey and not get displayed at all, that is, background-image: url(). Usually if I resize the window a couple more times, the image will finally appear. Does anyone know why this might be happening? Thank you for reading.

JS

function setParallaxImage() {


    const parallaxContainer = document.getElementsByClassName('paragraph--type--parallax-banner-with-text');

    for(var i = 0; i < parallaxContainer.length; i++) {
      console.log('in setparallax');
      var x = parallaxContainer[i];
      var parallax = x.getElementsByClassName('field--name-field-parallax-image-top-')[0];
      var picture = parallax.getElementsByTagName("picture")[0];
      var sourceURL = picture.querySelector('img').currentSrc;
      x.setAttribute('style', 'background-image: url(' + sourceURL +')');
      var img = picture.getElementsByTagName("img")[0].setAttribute('src', '/sites/default/files/src_images/dummy_image.gif');
    }
  }

window.onload = setParallaxImage
window.onresize = setParallaxImage;

HTML

<div class='paragraph--type--parallax-banner-with-text'>
 <div class='field--name-field-parallax-image-top-'>
  <picture>
   <!-- several source tags here -->
   <img src="will-be-given-dummy-image-in-JS">
  </picture>
 </div>
</div>

1

There are 1 answers

0
Dennis Bohn On

You can use the property "complete" to check, if the image was already loaded. If not, u can use the onload-Event to fire, when the image is available.

if (img.complete) {
    console.log(img.currentSrc);
} else {
    img.onload = function() {
        console.log(img.currentSrc);
    }
}