Lazy Loading Images in Javascript Example

Category: Loading | February 11, 2019
Author: verlok
Official Page: Go to Website
Last Update:August 1, 2023

It is important for any website to load its images faster for better user experience. Especially if you are running a wallpaper website which always has hundreds of images.

If you are facing slow speed then the Lazy loading images come to there to solve the issue. Today we are going to share you a lazy loading plugin which builds with javascript and also show you an example of how it works.

The lazyload.js is a stand-alone Javascript plugin without depending on jquery or any other dependencies. It supports the srcset attribute and speeds up your web application by loading the images as they enter the viewport.

Lazyload is a super fast, lightweight and flexible library which speeds up your website. It’s written in plain vanilla Javascript and use the IntersectionObserver.

It also supports responsive images and perfect for an SEO point of view. Not only this but it also comes with notable features.

Make Lazy Loading Photos in Javascript and Implementation

The use is dead simple and easy. All you need to load the library files before closing the head tab.

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

Next thing is to define the images. And Instead of defining the image path in default src attribute, you need to define the  data-original

<img alt="Phone One" data-original="image1.jpg" width="250" height="250">
<img alt="Phone Two" data-original="image2.jpg" width="250" height="250">
<img alt="Phone Three" data-original="image3.jpg" width="250" height="250">
<img alt="Phone Four" data-original="image4.jpg" width="250" height="250">

Now we need to Initialize the lazy load functionality and for this, you need to only call one JS line of code.

new LazyLoad();

If you want to customize its functionality you can do it by changing the default values of options.

// image selector
elements_selector: "img",

// parent container
container: window,

// the distance out of the viewport
threshold: 300,

// different thresholds
thresholds: null,

// data-src
data_src: "src",

// data-srcset
data_srcset: "srcset",

// date-sizes
data_sizes: "sizes",

// multiple background images
data_bg: "bg",

// default classes
class_loading: "loading",
class_loaded: "loaded",
class_error: "error",

// the time (in milliseconds) each image needs to stay inside the viewport before its loading begins.
load_delay: 0,

// callbacks
callback_load: null,
callback_set: null,
callback_set: null,
callback_enter: null

That’s It.