0

I am trying to optimize my site for lazy loading. The user will enter my site, using a media query and jQuery the size of the user's screen is detected, if the user's screen is < 420px then the mobile images will be loaded, if not the large images will be loaded. I have already made this possible:

HTML

<img src='/loading-img.jpg' data-large-src='/media/large-img' data-mobile-src='/media/mobile-img'>

jQuery

$(document).ready(function() {
    // run test on initial page load
    checkSize();

    // run test on resize of the window
    $(window).resize(function(){
      checkSize();
    });
});

//Function to the css rule
function checkSize(){
    if ($("#check_screen").css("display") == "none" ){
        $('img').each(function() {
        $(this).attr('src', $(this).attr('data-mobile-src'));
      });
    }

    else{
        $('img').each(function() {
        $(this).attr('src', $(this).attr('data-large-src'));
      });
    }
}

After detecting which images to display, I do not want them all to load. Instead, I want only the images that are displayed and 200px under the viewport to load. How do I accomplish this?

user2896120
  • 2,563
  • 2
  • 27
  • 67

1 Answers1

0

You are doing unnecessary work; HTML5 already provides a way to do this using the srcset and sizes attributes (in addition to the src attribute which is used as a fallback for older browsers).

Example Syntax:

<img src="fallback.png"
     srcset="small.png 400w, medium.png 800w, large.png 1200w">
gyre
  • 14,437
  • 1
  • 32
  • 46