Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect used srcset or picture tag source with JavaScript

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.)

like image 862
Tyler V. Avatar asked Feb 23 '16 19:02

Tyler V.


People also ask

What is srcset in image tag?

srcset defines the set of images we will allow the browser to choose between, and what size each image is. Each set of image information is separated from the previous one by a comma.

Does Srcset override SRC?

Yes it's valid. The src is used as a fallback if the browser doesn't support srcset.

What is source Srcset?

Definition and Usage. The srcset attribute specifies the URL of the image to use in different situations. This attribute is required when <source> is used in <picture> .

What does responsive images mean?

Responsive images are the set of techniques used to load the right image based on device resolution, orientation, screen size, network connection, and page layout. The browser should not stretch the image to fit the page layout, and loading it shouldn't result in time & bandwidth wastage.


1 Answers

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

document.getElementById('myImage').currentSrc;

Or...

jQuery('#myImage').prop('currentSrc');
like image 194
Tyler V. Avatar answered Oct 14 '22 21:10

Tyler V.