admin管理员组

文章数量:1405122

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

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

Share Improve this question asked Mar 22 at 8:24 RodrygoRodrygo 211 silver badge4 bronze badges 1
  • 1 It is not clear what you hope to optimise. I don't see in your considerations that a value of "lazy" will still have the image loaded immediately when it is in the viewport. The only thing that changes in that case is the moment that the load event fires. Without actual reproducible example it is hard to see what you expected and what the problem is. Also provide information on whether you have initialised the width/height of the images that load lazily. – trincot Commented Mar 22 at 9:13
Add a comment  | 

2 Answers 2

Reset to default 1

It seems difficult to visualize your problem. But you can try with the observer in your code.

Place this script in the section

(function() {
  // Run immediately, don't wait for DOMContentLoaded
  // Define the eager load limit based on viewport width
  let eagerLoadLimit = 0;
  
  if (window.innerWidth > 1024) {
    eagerLoadLimit = 8; // desktop pc
  } else if (window.innerWidth >= 768) {
    eagerLoadLimit = 6; // tablets
  } else {
    eagerLoadLimit = 3; // mobile
  }
  
  // Create a small observer to run as soon as elements appear
  const observer = new MutationObserver(function(mutations) {
    mutations.forEach(function(mutation) {
      if (mutation.addedNodes.length) {
        const images = document.querySelectorAll('.image-container img:not([loading])');
        if (images.length > 0) {
          images.forEach((img, index) => {
            img.loading = index < eagerLoadLimit ? "eager" : "lazy";
          });
          // Disconnect once we've processed images
          if (document.querySelectorAll('.image-container img').length >= eagerLoadLimit) {
            observer.disconnect();
          }
        }
      }
    });
  });
  
  // Start observing as early as possible
  observer.observe(document.documentElement, {
    childList: true,
    subtree: true
  });
})();

When you set loading="lazy", the browser only loads images that are visible or nearly visible. For a grid layout, this should already be fully optimized as all visible images will be loaded first. Setting these images to eager won't give you better performance.

本文标签: javascriptShould I use defer or DOMContentLoaded for modifying image loading attributesStack Overflow