Should I use defer or DOMContentLoaded for modifying image loading attributes?

I’m optimizing image loading for a grid layout (similar to YouTube thumbnails) by setting loading=”eager” for some images and loading=”lazy” for others based on screen size. I have placed the script tag in the head tag not the body to add loading attributes before images are in the DOM.

My goal is to:

  1. Run the script after the DOM is ready but before images load.

  2. Ensure optimal performance and avoid blocking rendering.

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";
    })
})

I was expecting better performance but I got worse performance in lighthouse