How to do lazy loading image with srcset?

前端 未结 3 1924
太阳男子
太阳男子 2021-02-05 20:23

I\'m using slick.js to build a carousel. However, even though I change the attribute from src to data-lazy the images still get loaded before I scroll

3条回答
  •  日久生厌
    2021-02-05 21:21

    lazySizes is just working fine. You need to alter your markup into something like this however.

    better_me
    

    Note srcset is changed to data-srcset and data-lazy is changed to data-src. Additionally you must add the class lazyload.

    Your sizes attribute didn't made too much sense. Maybe you want to use x descriptors instead? Or simply use sizes="200px"? I don't know. I simply switched it to data-sizes="auto", so it gets automatically calculated for you. (But in that case the image dimension has to be computable before the image is loaded.)

    lazySizes indeed loads images before they get in view. This is a big improvement for user experience. A user, who scrolls something into view doesn't want to wait then. A lazyloader that starts downloading an image after it is already in view disrupts the user experience.

    One nice thing about lazySizes is that this lazy loader checks whether the browser is currently heavily downloading and decides on this fact, whether it only downloads in view images or to also preload near view images.

    But if you don't want this you can control this by setting the lazySizes' expand and expFactor options.

提交回复
热议问题