12

When you're using srcset like this:

<img src="example-src.jpg" srcset="example-1x.jpg 1x, example-2x.jpg 2x" />

Or using a picture tag like this:

<picture>
   <source media="(min-width: 64em)" src="high-res.jpg">
   <source media="(min-width: 37.5em)" src="med-res.jpg">
   <source src="low-res.jpg">
   <img src="fallback.jpg" />
</picture>

Is it possible to find out what URL the browser decided to use? Checking the src attribute of the <img> tag itself doesn't actually tell you which image was loaded.

(Sorry if this is a duplicate. I can't find the solution to this anywhere.)

Tyler V.
  • 2,471
  • 21
  • 44

3 Answers3

22

You can use currentSrc in at least some browsers, (though I don't know which.)

document.getElementById('myImage').currentSrc;

Or...

jQuery('#myImage').prop('currentSrc');
Tyler V.
  • 2,471
  • 21
  • 44
  • 3
    I created a Pen to do a quick test. Just open the URL in various browsers to check: http://codepen.io/gapcode/full/pyojPd/ – Mario Feb 26 '16 at 20:54
  • 2
    `currentSrc` is a very helpful property and should probably solve 90% of cases, but does anyone knows how to find out which source of picture will be displayed, before image is actually loaded? – Vadim Kalinin Aug 26 '20 at 14:57
  • currentSrc is a property of a [HTMLMediaElement](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement). The source element is NOT a HTMLMediaElement. The img element is and therefore, if a srcset attribute is used in it, currentSrc will reflect which of the possible sources is currently active. – Stephen Miller Jul 14 '21 at 21:01
0

If you just want to now wich source is used:

  1. Use inspect (ctrl+shift+i).
  2. Go to the Network tab, be sure cache is disabeled and reload the page (F5 or ctrl + R).
  3. Select Img to shorten the list.

In the list you will find which image is loaded. If you change the screensize and reload, you will see the change in the results.

Henry
  • 1,242
  • 1
  • 12
  • 10
-1

This isn't possible at the moment, as far as I'm aware. I put a use case/feature request ("3.10 Managing source swapping between breakpoints") in for something almost identical to this to the RICG. So I hope it's still in the pipeline. But unfortunately it's not something that can be accessed at the moment.

Tom Kentell
  • 486
  • 3
  • 11