Lazy Loading HTML5 picture tag

前端 未结 3 893
陌清茗
陌清茗 2020-12-29 06:34

I have been searching (unsuccessfully) for a reliable method to lazy load images while using the HTML5 spec for . Most solutions/plugins out ther

3条回答
  •  醉话见心
    2020-12-29 06:43

    Working example of lazy loading images using the picture element and intersection observer tested in Chrome and Firefox. Safari doesn't support intersection observer so the images are loaded immediately, and IE11 doesn't support the element so we fallback to the default img

    The media queries in the media attr are arbitrary and can be set to suit.

    The width threshold set is 960px - try a reload above and below this width to see either the medium(-m) or large(-l) variation of the image being downloaded when the image is scrolled into the viewport.

    Codepen

    
    
      
      
      city
    
    
    
      
      
      forest
    
    
    
    
      
      
      river
    
    
    
      
      
      desert
    
    

    and the JS:

        document.addEventListener("DOMContentLoaded", function(event) {
       var lazyImages =[].slice.call(
        document.querySelectorAll(".lazy > source")
       )
    
       if ("IntersectionObserver" in window) {
          let lazyImageObserver = 
           new IntersectionObserver(function(entries, observer) {
              entries.forEach(function(entry) {
               if (entry.isIntersecting) {      
                  let lazyImage = entry.target;
                  lazyImage.srcset = lazyImage.dataset.srcset;
                  lazyImage.nextElementSibling.srcset = lazyImage.dataset.srcset;
                  lazyImage.nextElementSibling.classList.add('fade-in');
                  lazyImage.parentElement.classList.remove("lazy");
                 lazyImageObserver.unobserve(lazyImage);
                }
             });
            });
    
          lazyImages.forEach(function(lazyImage) {
           lazyImageObserver.observe(lazyImage);
          });
       } else {
         // Not supported, load all images immediately
        lazyImages.forEach(function(image){
            image.nextElementSibling.src = image.nextElementSibling.dataset.srcset;
          });
        }
      });
    

    One last thought is that if you change the screen width back and forth, the image files are repeatedly downloaded again. If I could tie the above method in to a cache check then this would be golden...

提交回复
热议问题