shinsenter / defer.js

🥇 A lightweight JavaScript library that helps you lazy load (almost) anything. Defer.js is dependency-free, highly efficient, and optimized for Web Vitals.
https://shinsenter.github.io/defer.js/
MIT License
277 stars 45 forks source link

Support for lazyloading background image set in CSS #96

Closed sabrina-zeidan closed 3 years ago

sabrina-zeidan commented 3 years ago

Is your feature request related to a problem? Please describe.

There is a described way currently to use defer.js to lazyload background images set via inline CSS. Is there a way to do the same with background images set in CSS like this #div { background: url(); }

Describe the solution you'd like

This solution works using Intersection observer. Is there a designed way to pass arguments to Defer.dom(); to do the same?

shinsenter commented 3 years ago

@sabrina-zeidan

Basically, the Defer.dom function converts the tag's data-* attributes to regular attributes when an element appears in the browser's viewport. Then the tag that is shown will also be added a class defer-loaded.

So there are at least three solutions to lazyload background image for any tag with Defer.dom:

  1. adding the data-style attribute.
  2. adding the data-class attribute.
  3. adding css has a background image attached to the defer-loaded class for that element.

I'm sorry that I'm on the train to work right now, and using my smartphone to answer you so I can't give you more specific example code yet. I think with these suggestions you will have a way to be able to do what you want.

sabrina-zeidan commented 3 years ago

@shinsenter thank you very much! I figured this out for images set as background via ID, added an update to docs. Haven't found a way to do the same when background is assigned to class, yet. (.class { background: url(); })

shinsenter commented 3 years ago

@sabrina-zeidan Thank you for your contribution. I will review and update the document to be more specific to the issue you raised.

shinsenter commented 3 years ago

@sabrina-zeidan Document is updated #98.