Chrome等浏览器优先加载JPG而非WebP格式图片问题排查
问题核心原因
<source>标签不支持src属性,必须使用srcset属性指定资源地址,这是Chrome等浏览器无法识别WebP资源、直接 fallback 到JPG/PNG格式的核心原因。
其他可优化的错误点
<source>标签上的class属性无效,类名只需加在最终的<img>标签上即可- 原生
height/width属性不需要加px单位,属性值仅需填写纯数字
修正后代码
普通图片场景
<picture> <source height="150" width="150" srcset="<?php echo get_stylesheet_directory_uri();?>/assets/pictures/section/logo_dsv_150x150.webp" type="image/webp"> <source height="150" width="150" srcset="<?php echo get_stylesheet_directory_uri();?>/assets/pictures/section/logo_dsv_150x150.png" type="image/png"> <img class="content_image" height="150" width="150" src="<?php echo get_stylesheet_directory_uri();?>/assets/pictures/section/logo_dsv_150x150.png" alt="lorem ipsum"> </picture>
ACF自定义字段场景
<?php $image_02_jpg = get_field('content_picture_02_jpg'); $image_02_webp = get_field('content_picture_02_webp'); ?> <picture> <source width="679" height="450" srcset="<?php echo $image_02_webp['url']; ?>" type="image/webp"> <source width="679" height="450" srcset="<?php echo $image_02_jpg['url']; ?>" type="image/jpeg"> <img class="content_image" width="679" height="450" src="<?php echo $image_02_jpg['url']; ?>" alt="content_image"> </picture>
补充检查项
如果修改后仍无法正常加载WebP,可直接在地址栏访问WebP资源的完整URL,确认资源可正常访问,不存在404、跨域或权限限制问题。
内容的提问来源于stack exchange,提问作者Timo Fingas
相关产品推荐
相关产品推荐

