You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WordPress中移除LCP图片懒加载失效问题求助

问题:WordPress移除首屏LCP图片懒加载属性失效排查与解决方案

问题背景

找到一个已有2年历史的解决方案,核心逻辑是统计页面中的<img>标签,移除第1个标签的loading属性,通过WordPress代码片段插件实现。但实际使用后,GTMetrix仍提示“请勿对LCP图片启用懒加载”,浏览器检查发现每篇文章的第一张(及所有)图片仍带有loading="lazy"属性。曾怀疑代码将头部站点Logo算作第一张图片,但Logo同样带有loading="lazy"属性,说明该代码完全未生效。

站点环境

  • WordPress 6.0.1
  • 主题:Hello Elementor Child
  • Elementor + Elementor Pro
  • JetEngine(用于自定义文章类型)
  • Imagify(用于WebP格式转换与优化)
  • 未运行任何额外懒加载插件,不想禁用WordPress全局懒加载,仅希望移除首屏LCP图片的懒加载属性

当前使用的代码片段

/* Remove lazy load first image */
function add_responsive_class($content)
{
    if ( is_single() || is_page() || is_front_page() || is_home() ) 
    {
        $content = mb_convert_encoding($content, 'HTML-ENTITIES', "UTF-8");
        $document = new DOMDocument();
        libxml_use_internal_errors(true);
        $document->loadHTML(utf8_decode($content));
        $imgs = $document->getElementsByTagName('img');
        $img = $imgs[0];
        if ($imgs[0] == 1) 
        { // Check first if it is the first image
            $img->removeAttribute( 'loading' );
            $html = $document->saveHTML();
            return $html;
        }
        else 
        {
            return $content;
        }
    }
    else 
    {
        return $content;
    }
}
add_filter ('the_content', 'add_responsive_class');

需求

恳请分析代码失效原因,或提供可行的替代解决方案。

内容的提问来源于stack exchange,提问作者Aurelian

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 19:48:23