DEV Community

Cover image for My first attempt to make script for Lazy-load images
Alex
Alex

Posted on

1

My first attempt to make script for Lazy-load images

This is very simple script, what make images to load only when they appear in your browser viewport. Why it's important you can read here here.

Script written on plain JavaScript, and it's weight <1 kb.

In html code it uses the same idea, as other similar scripts. Let's say you have image:

<img src='myCat.jpg'>

Change attribute src to data-src, so it will look like:

<img data-src='myCat.jpg'>

Script, when image appear in viewport will put value from data-src to newly created src attribute.

In first line of the script I put in array all the elements what I got by using getElementsByTagName():

var myImages = [...document.getElementsByTagName('img')];

This is because I don't know how to delete elements from the HTMLCollection, which I get using clearly document.getElementsByTagName('img'). So I put it into array, and can easily manipulate them.

I used:

document.addEventListener('scroll'

and function inside it, to check if image appear in viewport.

Inside of this function - simple for... cycle, which, using method getBoundingClientRect() will check, if image come in sight of viewport.

By using myImages.splice(i, 1) I remove already lazy-loaded image from array. When array empty - script stops:

if (myImages.length == 0) {
document.removeEventListener('scroll', lazyLoad);
}


I don't know how good or bad this script, but it works.
If someone find it useful I'll be happy 😊

Demo || Github

Tiugo image

Modular, Fast, and Built for Developers

CKEditor 5 gives you full control over your editing experience. A modular architecture means you get high performance, fewer re-renders and a setup that scales with your needs.

Start now

Top comments (0)

Neon image

Next.js applications: Set up a Neon project in seconds

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Get started →

👋 Kindness is contagious

Dive into this informative piece, backed by our vibrant DEV Community

Whether you’re a novice or a pro, your perspective enriches our collective insight.

A simple “thank you” can lift someone’s spirits—share your gratitude in the comments!

On DEV, the power of shared knowledge paves a smoother path and tightens our community ties. Found value here? A quick thanks to the author makes a big impact.

Okay