3

I have a lot of image/webp images and want the browser to have a fallback image/jpg for Safari.

For some reason Chrome (and every other browser) is still using the jpg image instead of the webp.

<picture>
     <source class="content_image" height="150" width="150" src="<?php echo get_stylesheet_directory_uri();?>/assets/pictures/section/logo_dsv_150x150.webp" type="image/webp">
     <source class="content_image" height="150" width="150" src="<?php echo get_stylesheet_directory_uri();?>/assets/pictures/section/logo_dsv_150x150.png" type="image/png">
     <img height="150" width="150" src="<?php echo get_stylesheet_directory_uri();?>/assets/pictures/section/logo_dsv_150x150.png" alt="lorem ipsum">
</picture>

I also have it in combination with ACF:

<?php
     $image_02_jpg = get_field('content_picture_02_jpg');
     $image_02_webp = get_field('content_picture_02_webp');
?>
<picture>
     <source class="content_image" width="679" height="450px" src="<?php echo $image_02_webp['url']; ?>" type="image/webp">
     <source class="content_image" width="679" height="450px" src="<?php echo $image_02_jpg['url']; ?>" type="image/jpeg"> 
     <img class="content_image" width="679" height="450px" src="<?php echo $image_02_jpg['url']; ?>" alt="content_image">
</picture>
Fenton
  • 241,084
  • 71
  • 387
  • 401
  • Does this help? https://stackoverflow.com/questions/57487066/chrome-is-defaulting-to-jpg-when-webp-is-available-why – Nico Haase Nov 25 '21 at 09:03
  • Or this? https://stackoverflow.com/questions/66312543/why-google-chrome-loads-jpg-instead-of-avif-and-webp – Nico Haase Nov 25 '21 at 09:03
  • Or this? https://stackoverflow.com/questions/62700342/picture-fallback-default-to-png-instead-of-webp – Nico Haase Nov 25 '21 at 09:04
  • 1
    @NicoHaase all of the links you are adding relate to where images are selected based on the `media` attribute. There is no `media` attribute in the original post. – Fenton Nov 25 '21 at 09:06

1 Answers1

3

Use the srcset attribute instead of src on the source element.

<?php
  $image_02_jpg = get_field('content_picture_02_jpg');
  $image_02_webp = get_field('content_picture_02_webp');
?>
<picture>
  <source srcset="<?php echo $image_02_webp['url']; ?>" type="image/webp">
  <source srcset="<?php echo $image_02_jpg['url']; ?>" type="image/jpeg"> 
  <img src="<?php echo $image_02_jpg['url']; ?>" alt="content_image">
</picture>

<source> Element

  • src: Required for <audio> and <video>, address of the media resource. The value of this attribute is ignored when the <source> element is placed inside a <picture> element.

  • srcset: A list of one or more strings separated by commas indicating a set of possible images represented by the source for the browser to use.

cam
  • 3,179
  • 1
  • 12
  • 15