Lazy-Loaded Images — Good Way program with javascript part-2

Shivam Gupta
3 min readJan 27, 2019

--

Today i will talk about IntersectionObserver and how to determine visibility of the element in DOM.

This is very useful tool —

you can use Infinite scroll, lazy loading images and animations.

Now you will learn 2 different ways to do this by plain javascript.

Intersection Observer is a browser API that can be used for the visibility of an element in the viewport.

Some website uses quicklink library for lazy loading there comments section.

  1. Lets started Writting lazy loading images bad code practice first —

first create a folder name lazy loaded images/

Create 3 files — index.html , app.js, style.css

index.html —

index.html

here we use —

<img data-lazy=’url’/>

we create custom attribute here data-lazy for now it will not work as img needs src attribute to load images so we will use data-lazy attribute to get url and load it ti DOM when required.

style.css

style.css

app.js

app.js

Understand code —

attach scroll event listener —

1st Store all images in a query selector —

const targets = document.querySelectorAll(“img”);

window.addEventListener(‘scroll’, () => {

on every scroll this method will call

});

now we have all dom inages in targets varriable som loop over all in every scroll and if the given image attribute is visible in our view so we add src attribute to image so that network call make and load image :)

const src = img.getAttribute(‘data-lazy’);

if(src) {

img.setAttribute(‘src’, src);// we put src attribute with image url to image

img.classList.add(‘fade’);.// to appear image with animation

}

On first load no network request will be make for image load when we start scrolling network requests make and lazy load images when image comes in viewport.

but this code is inefficient because each time listening to scroll event is very heavy process see —

Lots of scroll event

see 3000 consoles generate in some consoles.

See Bad Code in working —

Event listeners continue running even if all images loaded so its doing all calculation in the background to main thread.

2. Lets Do Proper approach using interSection Observer just change in app.js —

intersectionObserver
  1. We attached intersection observer to all images so by using this only if image is not loaded so network call eill be done.
  2. if all images in which observer attached loaded so no extra calculation will be done as onScroll event always call in not necessory.
  3. Code Assets
Lazy load images easy

Thanks please clap if you like my post. Any Question write in comment section.

Miss the first part ? take a look

--

--

Shivam Gupta
Shivam Gupta

Written by Shivam Gupta

Full Stack Engineer (Web/App) working on different JS Technologies & frameworks— Angular, Node, Typescript, Ionic, Firebase, AWS, ElK...Love to write cool stuff

No responses yet