Lazy Loading Images on the Web
At its most basic implementation always need to do:
- Build HTML with special data attribute
- Watch changes to the viewport or scrolling
- Swap the data attribute to src attribute
The first step is creating HTML element with data attribute:
getBoundingClientRect() to test whether an image is within the viewport:
Last, geting all of images that we want to lazy load and swap the
data-src value to
The following is some jquery plugins or libraries that can do similarly works:
Why we need this? Using this service to get responsive images. For example, we can upload a huge image in backend and download appropriate image based on the device’s screen size and pixel density to compresse response size.
Before generating different dimensions images, it’s better to use image compression tool to reduce file size, such like https://tinypng.com/.