Search code examples
htmlwebp

Image type webp. The browser load two formats


I have an error in my development when implementing .webp and .png images.

I don't get the browser to show one option (or another), and now my problem is that the browser loads the two images ( webp + png ) gand shows them in block.

I'm doing something wrong, of course, and I'm not sure of img tags either, but I'm using them in .css.

Any idea of ​​my mistakes?

Thanks in advance.

HTML:

<link rel=preload as=script href="js/modernizr.min.js"/>

<div id="info-1">
  <picture>
    <img class="imgesc" source srcset="img/Camiseta-1.png" type="image/png" width="725" height="1024" alt="imagen">
    <img class="imgesc" source srcset="img/Camiseta-1.webp" type="image/webp" width="725" height="1024" alt="imagen">

    <img class="imgmov" source srcset="img/Camiseta-1-Land.png" type="image/png" width="1024" height="725" alt="imagen">
    <img class="imgmov" source srcset="img/Camiseta-1-Land.webp" type="image/webp" width="1024" height="725" alt="imagen">
  </picture>
</div

Style:

#info-1 img {
  width:100%;
  height:auto;
  max-width:500px;
  margin:0 auto
}

.imgmov {
display:none
}

@media screen and (max-width:999px) and (orientation:landscape){
  .imgesc{display:none}
  .imgmov{display:block}
  #info-1{max-width:310px;margin:auto}
}

Solution

  • It's showing two copies of each image, because you have an <img> tag for each image format, including modern ones. That's not quite how fallback images work.

    If you're using a <picture> element, it should only contain <img> elements for backward-compatibility with older browsers. The modern image formats, targeted at modern browsers, should be in a <source> element instead.

    Read this: https://developer.mozilla.org/en-US/docs/Learn/HTML/Multimedia_and_embedding/Responsive_images#Use_modern_image_formats_boldly

    Here's the example code from the Mozilla docs, but with your filenames instead:

    <picture>
      <source type="image/webp" srcset="img/Camiseta-1.webp"> 
      <img src="img/Camiseta-1.png" alt="imagen">
    </picture>
    

    That documentation page also talks about how to use the size attribute to make resolution-specific fallbacks instead of format-specific ones.