Easy Lazy Loading Plugin For Images – lazyloading.js

Category: Javascript , Loading | August 15, 2022
Author:BaseMax
Views Total:111 views
Official Page:Go to website
Last Update:August 15, 2022
License:MIT

Preview:

Easy Lazy Loading Plugin For Images – lazyloading.js

Description:

It’s difficult to acquire the best possible user experience for your website (think about the users) when you have images that slow down your website. These large images may be beautiful photographs but bogging down page loads at a snail’s pace can create bad UX for users. This is one of the reasons image loading has grown in popularity.

Lazy loading is a performance-enhancing technique that delays the download of non-visible content until the user requests it. In the case of images, it prevents unnecessary roundtrips to the server from loading images that are not visible in the initial page load.

While the loading="lazy" attribute can delay the loading of images in a web page, the feature is not supported by all browsers. Developers who use it will see a shift in the way page images is loaded. This is not a significant problem for beginners in the industry though because most JavaScript lazy loading libraries are available for download. There are multiple methods that you can use to load images on your website.

In this example, we’re going to introduce you to a fresh new vanilla JavaScript library that enables lazy loading functionality on your site without having to add extra attributes (like data-src) to the original images. Have fun with it.

How to use it:

1. Download and import the lazyloading.js into the document.

<script src="lazyloading.js"></script>

2. Enable the lazy loading plugin on all images within the document.

document.querySelectorAll("img").forEach(img => {
  const src = img.getAttribute("src");
  if (src !== null) {
    img.setAttribute("data-src", src);
    // placeholder image
    img.setAttribute("src", "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7");
  }
});
var lazyloading = LazyLoading({
    'selector': 'img',
    'attribute': 'data-src'
});

You Might Be Interested In:


Leave a Reply