首页 > 解决方案 > WebP 后备图像未加载

问题描述

我正在使用<picture>标签来设置支持 WebP 的响应式图像。我正在提取同时具有.web.jpg文件的桌面图像和移动图像 URL。对于每种媒体,我都给出了.webp版本和.jpg版本。

我期望的是,如果该.webp版本不存在,则该网站将采用存在的 .jpg 文件。

知道这里有什么问题吗?

$image_desktop = get_field( 'desktop_image' ); // can be an .webp image or .jpg image
$image_mob     = get_field( 'mobile_image' ); // can be an .webp image or .jpg image
<picture>
  <source media="(min-width: 480px)"
  srcset="<?php echo esc_url( $image_desktop['url'] . '.webp' ); ?>"
  type="image/webp">

  <source srcset="<?php echo esc_url( $image_mob['url'] . '.webp' ); ?>" 
  type="image/webp">

  <source media="(min-width: 480px)" srcset="<?php echo esc_url( $image_desktop['url'] ); ?>"
  type="image/jpeg">

  <source srcset="<?php echo esc_url( $image_mob['url'] ); ?>" type="image/jpeg">

  <img class="header-image"
  src="<?php echo esc_url( $image_desktop['url'] ); ?>"
  alt="<?php echo esc_attr( $image_desktop['url'] ); ?>">
</picture>

标签: phphtmlwordpresswebpresponsive-images

解决方案


您放入srcset属性中的所有 URL 都必须有效并且必须存在。

支持 WebP 的浏览器将尝试从 加载 URL,<source type="image/webp">而所有其他浏览器将尝试从 加载 URL <source type="image/jpeg">。如果浏览器选择的 URL 不存在,则不会回退到其他<source>s 之一。

您应该检查服务器端的图像文件是否存在。


推荐阅读