Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- A very inefficient but with best browser support way would be to check if the
- clientBoundingRect of the image is currently inside the viewport or not on every
- scroll event, damn! it's costly!
- */
- /*
- Let's say the images in HTML are:
- <img data-src="someimage1.png" class="lazy-image">
- <img data-src="someimage2.png" class="lazy-image">
- <img data-src="someimage3.png" class="lazy-image">
- <img data-src="someimage4.png" class="lazy-image">
- <img data-src="someimage5.png" class="lazy-image">
- */
- /*
- Then the following javaSscript code
- */
- (function() {
- document.addEventListener('DOMContentLoaded', () => {
- let debouncedLazyLoad = null;
- function lazyLoad() {
- if(debouncedLazyLoad) {
- clearTimeout(debouncedLazyLoad);
- }
- debouncedLazyLoad = setTimeout(() => {
- const images = document.querySelectorAll('.lazy-image');
- /**
- Foreach image we need to check if it's TOP is less than page's height (This means
- the current immediate bottom)
- */
- const pageCurrentBottom = window.innerHeight;
- images.forEach((img) => {
- const imgTop = img.getBoundingClientRect().top;
- if(imgTop < pageCurrentBottom) {
- img.src = img.dataset.src;
- img.classList.remove("lazy-image");
- }
- }, 200);
- });
- }
- document.addEventListener('scroll', lazyLoad);
- });
- })();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement