Sep 8th, 2022

How to Lazy Load Images in Javascript

Author Picture

Dhairya Shah

Software Engineer

Images are an essential part of a website. Images are the heaviest part of a website which affects the loading time and affects the performance of the website.

If you are thinking about using it to implement lazy loading and doing all the tedious work, then you will be happy reading the next line.

We are gifted with a native browser API that will do all the work for us.

It can be as simple as adding the loading="lazy" to an Image element.

Let’s be lazy 😉

Let’s use the lazy loading in an actual code:

<img src="image.png" loading="lazy" onload="alert('Image has been loaded')"/>

If you have read the above code carefully, I have added an onload() callback function which states that the image has been loaded.

Loading can be of three types:

Try this live event:

See the Pen by Dhairya Shah (@dhairyathedev) on CodePen.

If your genius mind has questioned you about the browser support. Let’s answer it.

Browser support

Even while not all browsers completely support it, if one doesn’t, the image will still be displayed, thus there’s no harm in including it.

Can I use

Thanks for reading

Follow me on Twitter

Thanks for reading!