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 😊
Top comments (0)