Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When using picture, source and srcset how check which src was loaded? (img.src is empty)

I'm using the picture element with source's to choose which image to load. And while I can add a load listener, I cannot figure out which image was loaded as the img tag's src attribute and property are both empty, even when loaded!

<picture>
      <source srcset="images/test1.png" media="(min-width: 64em)">
      <source srcset="images/test2.png" media="(max-width: 63.99em)">

      <!-- This will alert an empty string "" -->
      <img srcset="images/test.png" alt="" onload="alert( this.src );">
</picture>

How do I determine which image was loaded?

like image 557
Don Rhummy Avatar asked Dec 19 '15 00:12

Don Rhummy


People also ask

Does Srcset override SRC?

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

Does Srcset load all images?

Each image in srcset can be taken. So if you want to control, what is used or not used, you need to use the picture element.

How does IMG Srcset work?

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.


1 Answers

In modern browsers that implement this, there appears to be a new property: currentSrc. In the image.onload, you can check for this. In older browsers, it will use src.

img.onload = function()
{
    //Old browser
    if ( typeof img.currentSrc === "undefined" ) console.log( img.src );

    //Modern browser
    else console.log( img.currentSrc );
}
like image 68
Don Rhummy Avatar answered Sep 19 '22 15:09

Don Rhummy