4

I've been trying to have a certain image tag behave responsively, by retrieving the most appropriate src depending on context.

The tag looks like this:

<img
    id="picimg"

    src="image.jpg"

    srcset="image-300x281.jpg 300w,
            image-1024x961.jpg 1024w,
            image.jpg 1664w"

    sizes="(max-width: 499px) 92vw,
            (min-width: 500px) 86vw,
            (min-width: 960px) 96vw, 96vw"
>

I have even tried this code snippet (found at : http://blog.cloudfour.com/responsive-images-101-part-2-img-required/) to check which src is in effect each time.

(function() {
  var currentSrc, oldSrc, imgEl;
  var showPicSrc = function() {
    oldSrc     = currentSrc;
    imgEl      = document.getElementById('picimg');
    currentSrc = imgEl.currentSrc || imgEl.src;

    if (typeof oldSrc === 'undefined' || oldSrc !== currentSrc) {
      document.getElementById('logger').innerHTML = currentSrc;
    }
  };

  // You may wish to debounce resize if you have performance concerns
  window.addEventListener('resize', showPicSrc);
  window.addEventListener('load', showPicSrc);
})(window);

However, the src seems to never change (it seems to always be image.jpg), regardless of the browser and its width.

I suspect that, by repeating the same default src as the last item in the srcsetattribute, it may be affecting the outcome. Or else, maybe the determinant factor is the default size (last item in sizes).

Your help would be much appreciated.

j08691
  • 204,283
  • 31
  • 260
  • 272

2 Answers2

2

If you start out with a wide window such that the biggest image is the most appropriate one, then Chrome/Opera will not download a smaller image when making the window smaller. See https://stackoverflow.com/a/28368483/729033

Community
  • 1
  • 1
zcorpan
  • 1,243
  • 6
  • 11
0

It seems like the syntax is working correctly (it tested successfully on actual mobile browsers).

I just don't know exactly why the script to check the src didn't work properly.

Thank you all for your help.