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

网格布局图片加载优化:DOMContentLoaded与defer的选择及Lighthouse性能下降问题咨询

网格布局图片加载优化:DOMContentLoaded与defer的选择及Lighthouse性能下降问题咨询

我正在为类似YouTube缩略图的网格布局做图片加载优化,打算根据屏幕尺寸给部分图片设置loading="eager",其余设置loading="lazy"。我把脚本标签放在了<head>而非<body>里,想在图片进入DOM之前就添加加载属性。

我的目标是:

  • 让脚本在DOM就绪但图片尚未加载时运行
  • 确保最优性能,避免阻塞渲染

以下是我的代码:

document.addEventListener("DOMContentLoaded", function(){
    let image = document.querySelectorAll(".image-container img");
    let eagerLoadLimit = 0

    if(window.innerWidth > 1024){
        eagerLoadLimit = 8 // desktop pc
    }
    else if(window.innerWidth >= 768 && window.innerWidth < 1024){
        eagerLoadLimit = 6 // tablets
    }
    else{
        eagerLoadLimit = 3; // mobile
    }
    image.forEach((img, index) =>{
        img.loading = index < eagerLoadLimit ? "eager" : "lazy";
    })
})

我原本以为这样能提升性能,但Lighthouse测试结果反而显示性能下降了,想问问大家这是怎么回事,该怎么调整?

备注:内容来源于stack exchange,提问作者Rodrygo

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.13 19:24:49