How to use lazySizes with angular | Responsive Images

Suryaprakash
Jun 15, 2024

--

What is lazySizes ?

lazySizes is the ultimate and lightweight lazyLoader which lazy loads images (including responsive images (picture/srcset)), iframes and scripts. It is written in VanillaJS and with high performance in mind.

Below is the npm command to run in cmd to install lazySizes

npm install lazysizes --save

Then add it to your scripts in angular.json

"scripts": ["node_modules/lazysizes/lazysizes.min.js"]

That’s it. Now you have done setup successfully.

<img
data-src="../assets/landscape.jpg"
data-srcset="../assets/potrait.jpg 7000w,
../assets/potrait.jpg 1000w,
../assets/landscape.jpg 2000w" class="lazyload"
style="height:90vh" />

I have added 2 images with different ratios and choosed one for potrait and other for landscape.

potrait image at 630p width
Landscape image at 1200p width

For the same image tag, the displayed image changes based on the width of the page. I have demonstrated the use of lazySizes, but there are many use cases for this functionality.

--

--

Suryaprakash
Suryaprakash

Written by Suryaprakash

Angular Architect @PlateauCorp. Expert in Angular and .Net Core.

No responses yet