BrownBe
BrownBe

Reputation: 987

All images are loaded immediately with lazySizes plugin

I have a problem with my dynamic integration of Lazysizes plugin. The fact is when I load the page (cache disable), all images of the src are loaded with the content. After this, responsives images are lazy-loaded like I want.

My reflection :

Here my jquery script at the bottom of the page :

//lazy init
window.lazySizesConfig = window.lazySizesConfig || {};
lazySizesConfig.loadMode = 2;   
lazySizesConfig.preloadAfterLoad = false;
$('img').addClass('lazyload');

$("img.lazyload").each(function() { 
    var src = $(this).attr('src').replace(/\.jpg$/i, "");
    $(this).attr("data-sizes","auto"); 
    $(this).attr("data-srcset", 
      src + '-240.jpg 240w,' + 
      src + '-360.jpg 360w,' + 
      src + '-480.jpg 480w, ' + 
      src + '-720.jpg 720w,' + 
      src + '-768.jpg 768w,' + 
      src + '-960.jpg 960w,' + 
      src + '-1280.jpg 1280w'
    ); 
    $(this).attr(
       "src",
       "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=="
    );
});   

I would like only responsive img is load when it is in the viewport. any idea about my issue ?

thanks

Upvotes: 1

Views: 8175

Answers (2)

halfzebra
halfzebra

Reputation: 6797

The issue that you're having is caused by the fact, that you're using JavaScript, to set the data-sizes and data-srcset attributes.

lazySizes script expects you to specify all of that in your HTML output.

You have to make sure that jQuery will be loaded, and your script will be executed before lazysizes.js.

I can't guarantee for any of my advice below to be useful, because this script is not intended to be used like that. Still, if you really want to get it to work with jQuery script from your question, consider the following:

  1. Remove async attribute from lazysizes <script> tag.
  2. Set lazySizesConfig.preloadAfterLoad = true;
  3. Run your script right after jQuery is loaded, doesn't matter where you put the script, just make sure it's executed before lazySizes and on $(document).ready().
  4. Only if all above is done, the lazySizes should lazyload the images as expected.

Upvotes: 2

Ivijan Stefan Stipić
Ivijan Stefan Stipić

Reputation: 6668

  1. You first need to specify data- atributtes.
  2. Load HTML
  3. Load jQuery and lazysizes.js
  4. Get all data- and save in variable
  5. Handle with it

I don't know if lazysizes.js have inside script some document ready function or some DOM change sniffer but I think you need a different approach.

Upvotes: -1

Related Questions