Show Images Only If They Are In Viewport – ldlazy

Category: Image , Javascript , Loading | February 3, 2022
Author:loadingio
Views Total:81 views
Official Page:Go to website
Last Update:February 3, 2022
License:MIT

Preview:

Show Images Only If They Are In Viewport – ldlazy

Description:

ldlazy is a Vanilla JavaScript lazy loading library that shows images only if they are in the viewport.

It detects the visibility change of your images using the IntersectionObserver API and applies visibility and opacity classes to those images when they’re scrolled into view.

How to use it:

1. Load the ldlazy library in the document.

<link rel="stylesheet" href="/dist/index.min.css" />
<script src="/dist/index.min.js"></script>

2. Initialize the ldlazy and determine in which container the library detects visibility change.

ldlz = new ldlazy({
  root: document.body,
});

3. Add the ldlz class to the target image and define the image path using the data-src attribute:

<img class="ldlz" data-src="1.png" />

4. Optionally, you can add a placeholder to the image as follows:

<img class="ldlz" src="data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs=" data-src="1.png" width="800px" height="600px" />

5. Perform a function when the visibility changes.

ldlz = new ldlazy({
  root: document.body,
  toggle: function(n) { 
    // ...
  },
});

You Might Be Interested In:


Leave a Reply